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

在Python字典中交换键和值(包含列表),python,Python,我有一本参考词典,主题和页码如下: reference = { 'maths': [3, 24],'physics': [4, 9, 12],'chemistry': [1, 3, 15] } 我需要帮助写一个函数来反转引用。也就是说,返回一个以页码为键的字典,每个字典都有一个相关的主题列表。例如,在上述示例上运行的swap(reference)应该返回 { 1: ['chemistry'], 3: ['maths', 'chemistry'], 4: ['physics'], 9: ['p

我有一本参考词典,主题和页码如下:

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']}
{1: ['chemistry'], 3: ['maths', 'chemistry'], 4: ['physics'], 9: ['physics'], 12: ['physics'], 15: ['chemistry'], 24: ['maths']}
不从
集合导入

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: ['chemistry'], 3: ['maths', 'chemistry'], 4: ['physics'], 9: ['physics'], 12: ['physics'], 15: ['chemistry'], 24: ['maths']}
reference={‘数学’:[3,24],‘物理’:[4,9,12],‘化学’:[1,3,15]}
表=[]
newReference={}
有关输入参考:
值=参考[键]
对于值中的值:
表.追加((值,键))
对于表中的x:
如果newReference.keys()中的x[0]:
newReference[x[0]]=newReference[x[0]]+[x[1]]
其他:
新引用[x[0]]=[x[1]]
打印(新参考)

谢谢,这真是一把利弗刀。但是,如果不使用任何导入的库,是否还有其他方法呢?上述方法适用于我选择的随机示例,但我现在发现,如果某些页面相同,则不幸的是,上述方法不起作用。例如:reference={'a':[1],'b':[1],'c':[1]}将给出{1:['c']}并忽略'a'和'b'@Pompi,这很奇怪,因为当我在您发布的新
reference
变量上运行此代码时,我得到了以下输出:
{1:['a',c',b']}
a
b
不会被忽略。嗨,Bernd,上面的例子对于我选择的随机例子是有效的,但是我现在发现,如果一些页面是相同的,那么上面的例子很不幸就不起作用了。例如:reference={'a':[1],'b':[1],'c':[1]}将给出{1:['c']}并忽略'a'和'b'嗨,Pompi,我想知道您是否可以检查python安装。我使用了您的输入并按预期获得了
{1:['b','c','a']}