简体   繁体   English

在列表的字典中切换键和值

[英]switch key and values in a dict of lists

Hello Stackoverflow people, 您好Stackoverflow的人,

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. 我有一个将列表作为值的嵌套字典,我想创建一个dict,其中所有列表条目都将其对应的键作为值。

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! 任何帮助都感激不尽!

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 希望能帮助到你

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

assuming your key: value dictionary contains list as a value and using dict comprehension. 假设您的key: value字典包含list作为值并使用dict理解。

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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM