I have a dictionary that has English words as keys and Finnish words as values. I'm trying to make a function to reverse this dictionary.
For example:
dictionary = {'move':['liikutta'], 'six':['kuusi'], 'fir':['kuusi']}
Expected output:
reverse = {'liikutta':['move'], 'kuusi':['six'], 'kuusi':['fir']}
The codes I'm using:
def reverse_dictionary(dictionary):
reverse = {}
for key, value in dictionary.items():
for i in range(len(value)):
reverse.update({value[i]:[key]})
return reverse
The 2nd item in the dictionary was skipped. I guess it was because the repeated 'kuusi', but I don't know how to solve it.
Output
{'liikutta':['move'], 'kuusi':['fir']}
Thanks all!
CodePudding user response:
Every key in a dictionary has to be unique. What you can do, is update the list.
dictionary = {'move': ['liikutta'], 'six': ['kuusi'], 'fir': ['kuusi']}
def reverse_dictionary(dictionary):
reverse = dict()
for key, value in dictionary.items():
l = reverse.get(value[0], []) # get the list or an empty list
l.append(key) # append the key
reverse.update({value[0]: l}) # update the dictionary
return reverse
reverse_dictionary(dictionary)
output:
{'liikutta': ['move'], 'kuusi': ['six', 'fir']}
In one line:
reverse.update({value[0]: reverse.get(value[0], []) [key]})
CodePudding user response:
If you use a list as a value - as it is in the original dictionary - then you can do it like this.
from collections import defaultdict
def reverse_dictionary(dictionary):
reverse = defaultdict(list)
for key, values in dictionary.items():
for value in values:
reverse[value].append(key)
return reverse
dictionary = {'move': ['liikutta'], 'six': ['kuusi'], 'fir': ['kuusi']}
print(reverse_dictionary(dictionary))
The result is defaultdict(<class 'list'>, {'liikutta': ['move'], 'kuusi': ['six', 'fir']})
.
A defaultdict
behaves like a normal dictionary, but it calls a factory function to supply missing values. In this case it's a list
.
CodePudding user response:
The straight and simple answer is NO. You can't have duplicate keys in a dictionary in Python, the keys should be unique in, And if you attempt to do so,it will just overwrite the previous value of the key.But you can have multiple values associated to a key
CodePudding user response:
You can try:
dictionary = {'move':['liikutta'], 'six':['kuusi'], 'fir':['kuusi']}
reverse = {}
for key, value in dictionary.items():
for i in value:
if i in reverse.keys():
reverse[i].append(key)
else:
reverse[i]=[key]
print(reverse)
Result:
{'liikutta': ['move'], 'kuusi': ['six', 'fir']}
CodePudding user response:
Try this:
def revd(d):
r = {}
for k,v in d.items():
for i in v:
# below is ternary expression, it updates r
r[i].append(k) if i in r else r.setdefault(i,[k])
return r
Side remark: Instead of
for i in range(len(value)):
use
for i, v in enumerate(value))