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

时间:2017-09-12 13:33:18

标签: python

我有一个参考字典,主题和页码如下:

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'] }

2 个答案:

答案 0 :(得分:6)

您可以使用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']}

答案 1 :(得分:0)

   
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)