Hello I am having trouble making a function that reverses any dictionary given to it but without any special libraries. For example
D = {one:uno, two:dos}
would return that dictionary as D = {uno:one, dos:two}
I am asking the reverse order for both the key and value not just key, this is very different
Try this:
result = dict((v,k) for k,v in d.items())
Example:
d = {'one':'uno', 'two':'dos'}
result = dict((v,k) for k,v in d.items())
print(result) # prints - {'uno': 'one', 'dos': 'two'}
What is happening here?
(v,k) for k,v in d.items() - You first iterate over all the (key, value) pairs in the dictionary and create tuples of (value, key).
Then you call dict() to create dictionary from the tuples.
Related
I have the following dictionary:
d = {}
d[1] = 'a'
d[2] = 'b'
d[3] = 'c'
d[4] = 'd'
I'd like to perform a reverse dictionary lookup for each character in a string:
input_string = "bad"
I get different results when I do this in a list comprehension as opposed to a nested for loop, and I don't understand why. As I understand, the list comprehension and the nested for loop should yield identical results. The list comprehension yields a list whose results are not in the order I would expect. My desired result here is that which is provided by the nested for loop, however I prefer to use the list comprehension to accomplish that. Perhaps this has something to do with python dictionary order of which I am unaware?
result1 = [key for key, value in d.items() for i in input_string if i == value]
print(result1)
> [1, 2, 4]
result2 = list()
for i in input_string:
for key, value in d.items():
if i == value:
result2.append(key)
print(result2)
> [2, 1, 4]
In order to mimic the traditional loop, the outer loop should be over input_string and the inner loop should be over d in the list comprehension:
out = [k for i in input_string for k,v in d.items() if i==v]
Output:
[2, 1, 4]
dict1 = {'Key1':[99,98,97],'Key2':[89,82,85]}
how to sum the values of key1 in python3 if the values in the format of list.
Just use sum() on the dict[key] e.g.
dict1 = {'Key1':[99,98,97],'Key2':[89,82,85]}
r = sum(dict1['Key1'])
print(r)
>> 294
Or if you mean you want to sum the first key of the dict, not necessarily 'Key1' then you can do it in a loop
dict1 = {'Key1':[99,98,97],'Key2':[89,82,85]}
for _, val_list in dict1.items(): # loop over list
r = sum(val_list) # sum the list
break
print(r)
>> 294
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.
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'}}
dict_data = {'c': ['d\n', 'e\n'], 'm':['r\n','z\n','o']}
a dictionary dict_data remove '\n' in the values
(order is not important.):
should return: {'c': ['d', 'e'], 'm':['r','z','o']}
This is what I tried:
def dicts(dict_data):
for k, v in dict_data.items():
for i in v:
f = i.strip('\n')
return f
How can i get this without doing anything to complicated?
You were on the right approach but you've probably assumed that altering i with i.strip('\n') in for i in v might make the change appear in dict_data. This isn't the case. What you're doing is altering i and then discarding the result.
A correct approach would be to build a list of the stripped elements and re-assign to the corresponding dictionary key:
def strip_dicts(dict_data):
for k, v in dict_data.items():
f = []
for i in v:
f.append(i.strip('\n'))
dict_data[k] = f
of course, remember, this alters the argument dictionary in-place.
You can create a different function that returns a new dictionary by using a comprehension:
def strip_dicts(d):
return {k: [i.strip() for i in v] for k,v in d.items()}