switch key and values in a dict of lists

大憨熊 提交于 2019-12-11 17:50:57

问题


Hello Stackoverflow people,

I have a nested dictionary with lists as values and I want to create a dict where all the list entries get their corresponding key as value.

Example time!

# what I have
dict1 = {"A":[1,2,3], "B":[4,5,6], "C":[7,8,9]}

# what I want
dict2 = {1:"A", 2:"A", 3:"A", 4:"B", 5:"B", 6:"B", 7:"C", 8:"C", 9:"C"}

Any help will be much appreciated!


回答1:


Try this

dict1 = {"A":[1,2,3], "B":[4,5,6], "C":[7,8,9]}
dict2= {}
for keys,values in dict1.items():
    for i in values:
        dict2[i]=keys
print(dict2)

Output

{1: 'A', 2: 'A', 3: 'A', 4: 'B', 5: 'B', 6: 'B', 7: 'C', 8: 'C', 9: 'C'}

Hope it helps




回答2:


Use dictionary comprehension:

d = {'a': 'b', 'c': 'd', 'e': 'f'}
d2 = dict((v1, k) for k, v in d.items() for v1 in v)  # Here is the one-liner



回答3:


assuming your key: value dictionary contains list as a value and using dict comprehension.

Using a second loop to iterate over the list present in original dictionary.

{item: key for key, value in dict1.items() for item in value}


来源:https://stackoverflow.com/questions/54422204/switch-key-and-values-in-a-dict-of-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!