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



我有一个带有主题和页码的参考字典:

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

我需要帮助编写倒置引用的功能。也就是说,返回带有页码作为键的字典,每个字典都带有关联的主题列表。例如,在上面的示例上运行的交换(参考)应返回

{ 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)

最新更新