I am trying to convert this dictionary:
dict1={x: ['John', 'Jack'], y: ['Julia', 'Michael']}
to this form:
dict2={'Julia': y, 'John': x, 'Jack': x, 'Michael': y}
I researched that a lot but I could not find anything.How can I do that?
CodePudding user response:
You can first get all the values from dict1 as your new keys then iterate over the dict1 and test if you key exists in the values of key-dict1.
keys = [element for val in list(dict1.values()) for element in val]
dict2 = dict()
for key in dict1.keys():
for k in keys:
if k in dict1.get(key):
dict2[k] = key
dict2
output
{'Julia': y, 'John': x, 'Jack': x, 'Michael': y}
CodePudding user response:
Easy as pie using a Dictionary Comprehension:
dict1 = {'x': ['John', 'Jack'], 'y': ['Julia', 'Michael']}
dict2 = {'Julia': 'y', 'John': 'x', 'Jack': 'x', 'Michael': 'y'}
dict3 = {
elem: key
for key, list_value in dict1.items()
for elem in list_value
}
assert dict2 == dict3
You're welcome. However, please not that if one of the letters appear in several lists, only the last occurrence will be taken into account, for example:
dict1 = {'x': ['Jack'], 'y': ['Jack']}
dict3 = {
elem: key
for key, list_value in dict1.items()
for elem in list_value
}
print(dict3) # {'Jack': 'y'}
CodePudding user response:
Alternatively, you can use itertools
:
import itertools
dict2 = dict(itertools.chain.from_iterable([zip(v,len(v)*k) for k, v in dict1.items()]))
CodePudding user response:
This is a simple operation, and it is not recommended to use multi-loop dictionary analysis. In general, you should try to keep the code simple and easy to read when it is not necessary. If there is a key conflict between the dictionaries, you should also write comments to ensure that others can fully understand.
new_dict = {}
for value, keys in dict1.items():
for key in keys:
new_dict[key] = value