swap the keys and values in a dictionary by storing the user input in dic - python-3.x

First the input should be dic length consider 3. then the input to a dic is keys and values separated by spaces i,e
"A 1
B 2
C 1"
now dic={A:1, B:2, C:1}
At first the keys and values and should be swapped, and if there are same keys and there values should be merged in a list and assigned to the same key as shown below.(these program should work for any length of dictionary)
the output should be dicout={1:['A','C'], 2:B}.
Thank you.

Define:
from collections import defaultdict
def make_dict(s):
d = defaultdict(list)
xs = s.split(" ")
for k, v in zip(xs[1::2], xs[::2]):
d[k].append(v)
for k, v in d.items():
if len(v) == 1:
d[k] = v[0]
return dict(d)
Example usage:
>>> make_dict("A 1 B 2 C 1")
{'1': ['A', 'C'], '2': 'B'}

Related

Check for multiple kv in a dictonary with a twist

I have a search list of dicts that I need to check if exist in another source dict.
source_dict = { 'a':'1', 'blue':'yes', 'c':'3' }
search_list = [ {'a':'1', 'b':'2'}, {'blue': 'yes'} ]
The items in the list all need to be checked however, we need a AND for all items in the same dict. OR between dicts in the list.
How would I start to tackle this problem?
You can use any and all:
>>> # the `OR` (`any`) of the `AND`s (`all`s) for each dict
>>> any(all(k in source_dict and source_dict[k] == v for k, v in d.items()) for d in search_list)
True
>>> # the `AND`s (`all`s) for each dict
>>> [all(k in source_dict and source_dict[k] == v for k, v in d.items()) for d in search_list]
[False, True]
any(map(lambda x: all(map(lambda k: source_dict[k] == x[k] if k in source_dict else False, x.keys())), search_list))

keep certain values in a dictionary values based on list

I have a dictionary d
d = {'1': ['Fisherman', 'fam', '125', '53901', 'funny'],
'2': ['Joi', '521', 'funny','fun', '1245']}
and a list l
l = ['521', 'Fisherman', 'fun','A2ML1', 'A3GALT2','funny']
I want to keep values in d that are not in l. I want my output to be
d_list = {'1': ['fam','125', '53901'],'2': ['Joi', '1245']}
To do so, I tried this
d_list = []
for k, v in d.items():
if v not in l:
d_list.append(v)
But this doesn't give me what I want. What can I do to my code (or new code) to get my desired d_list?
v is a list not a str
try this code:
d1 = {}
for k, v in d.items():
d1[k] = [i for i in v if i not in l]
d1
output:
{'1': ['fam', '125', '53901'], '2': ['Joi', '1245']}
you can doe it like this also
{key:set(values) - set(l) for key, values in d.items()}
or if you want values to be list instead of set
{key:list(set(values) - set(l)) for key, values in d.items()}

Accessing nested list and dictionaries

A = {'a':1, 'b':2, 'c':3}
B = {1:['a', 'b', 'c']}
The answer I need is to get the key from B and for each element in its value, which is a list, replace it with its value from A, like the following:
D = {1:[1,2,3]}
A[B[1][0]] - will give you the value of 'a'
A[B[1][1]] - will give you the value of 'b' and so on...
Here is mt solution:
A = {'a':1, 'b':2, 'c':3}
B = {1:['a', 'b', 'c']}
D = {}
for key, value in B.items():
D[key] = []
for oneValue in value:
D[key].append(A[oneValue]);
print D;
This will work for you:
A = {'a':1, 'b':2, 'c':3}
B = {1:['a', 'b', 'c']}
for key, value in B.items(): # loop in dict B
# loop in every list in B, use items as key to get values from A
# default to None if key doesn't exists in A and put it in a new temp list
l = [A.get(x, None) for x in value]
# Simplified version of line above
# l = []
# for x in value:
# l.append(A.get(x, None))
D[key] = l # use key of B as key and your new list value and add it to D
Or if you like to be too cleaver then:
# Doing same things as the last example but in one line
# which is hard to read and understand. Don't do this
D = {k: [A.get(x, None) for x in v] for k, v in B.items()}
In place editing B:
for key in B.keys():
for i in range(len(B[key])):
B[key][i] = A[B[key][i]]
Create a new D for returning
D = B.copy()
for key in D.keys():
for i in range(len(D[key])):
D[key][i] = A[D[key][i]]
I tested the code and it worked.

return dictionary of file names as keys and word lists with words unique to file as values

I am trying to write a function to extract only words unique to each key and list them in a dictionary output like {"key1": "unique words", "key2": "unique words", ... }. I start out with a dictionary. To test with I created a simple dictionary:
d = {1:["one", "two", "three"], 2:["two", "four",
"five"], 3:["one","four", "six"]}
My output should be:
{1:"three",
2:"five",
3:"six"}
I am thinking maybe split in to separate lists
def return_unique(dct):
Klist = list(dct.keys())
Vlist = list(dct.values())
aList = []
for i in range(len(Vlist)):
for j in Vlist[i]:
if
What I'm stuck on is how do I tell Python to do this: if Vlist[i][j] is not in the rest of Vlist then aList.append(Vlist[i][j]).
Thank you.
You can try something like this:
def return_unique(data):
all_values = []
for i in data.values(): # Get all values
all_values = all_values + i
unique_values = set([x for x in all_values if all_values.count(x) == 1]) # Values which are not duplicated
for key, value in data.items(): # For Python 3.x ( For Python 2.x -> data.iteritems())
for item in value: # Comparing values of two lists
for item1 in unique_values:
if item == item1:
data[key] = item
return data
d = {1:["one", "two", "three"], 2:["two", "four", "five"], 3:["one","four", "six"]}
print (return_unique(d))
result >> {1: 'three', 2: 'five', 3: 'six'}
Since a key may have more than one unique word associated with it, it makes sense for the values in the new dictionary to be a container type object to hold the unique words.
The set difference operator returns the difference between 2 sets:
>>> a = set([1, 2, 3])
>>> b = set([2, 4, 6])
>>> a - b
{1, 3}
We can use this to get the values unique to each key. Packaging these into a simple function yields:
def unique_words_dict(data):
res = {}
values = []
for k in data:
for g in data:
if g != k:
values += data[g]
res[k] = set(data[k]) - set(values)
values = []
return res
>>> d = {1:["one", "two", "three"],
2:["two", "four", "five"],
3:["one","four", "six"]}
>>> unique_words_dict(d)
{1: {'three'}, 2: {'five'}, 3: {'six'}}
If you only had to do this once, then you might be interested in the less efficeint but more consice dictionary comprehension:
>>> from functools import reduce
>>> {k: set(d[k]) - set(reduce(lambda a, b: a+b, [d[g] for g in d if g!=k], [])) for k in d}
{1: {'three'}, 2: {'five'}, 3: {'six'}}

How can i check if a string has some of the same characters in it in Python?

In my program, when a user inputs a word, it needs to be checked for letters that are the same.
For example, in string = "hello", hello has 2 'l's. How can i check for this in a python program?
Use a Counter object to count characters, returning those that have counts over 1.
from collections import Counter
def get_duplicates(string):
c = Counter(string)
return [(k, v) for k, v in c.items() if v > 1]
In [482]: get_duplicates('hello')
Out[482]: [('l', 2)]
In [483]: get_duplicates('helloooo')
Out[483]: [('l', 2), ('o', 4)]
You can accomplish this with
d = defaultdict(int)
def get_dupl(some_string):
# iterate over characters is some_string
for item in some_string:
d[item] += 1
# select all characters with count > 1
return dict(filter(lambda x: x[1]>1, d.items()))
print(get_dupl('hellooooo'))
which yields
{'l': 2, 'o': 5}

Resources