繁体   English   中英

在Python字典中交换键和值(包含列表)

[英]Swap around key and value (containing a list) within a Python dictionary

我有一本带有主题和页码的参考字典,如下所示:

reference = { 'maths': [3, 24],'physics': [4, 9, 12],'chemistry': [1, 3, 15] }

我需要编写反转引用的函数的帮助。 也就是说,返回一个以页码为键的字典,每个字典都有一个相关的主题列表。 例如,在上面的示例上运行的swap(reference)应该返回

{ 1: ['chemistry'], 3: ['maths', 'chemistry'], 4: ['physics'], 
9: ['physics'], 12: ['physics'], 15: ['chemistry'], 24: ['maths'] }

您可以使用defaultdict

from collections import defaultdict

d = defaultdict(list)
reference = { 'maths': [3, 24],'physics': [4, 9, 12],'chemistry': [1, 3, 15] }
for a, b in reference.items():   
    for i in b:    
        d[i].append(a)
print(dict(d))

输出:

{1: ['chemistry'], 3: ['maths', 'chemistry'], 4: ['physics'], 9: ['physics'], 12: ['physics'], 15: ['chemistry'], 24: ['maths']}

不从collections导入:

d = {}
for a, b in reference.items():
    for i in b:
        if i in d:
           d[i].append(a)
        else:
           d[i] = [a]

输出:

{1: ['chemistry'], 3: ['maths', 'chemistry'], 4: ['physics'], 9: ['physics'], 12: ['physics'], 15: ['chemistry'], 24: ['maths']}
reference = {'maths': [3, 24], 'physics': [4, 9, 12], 'chemistry': [1, 3, 15]} table = [] newReference = {} for key in reference: values = reference[key] for value in values: table.append((value, key)) for x in table: if x[0] in newReference.keys(): newReference[x[0]] = newReference[x[0]] + [x[1]] else: newReference[x[0]] = [x[1]] print(newReference)

暂无
暂无

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

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