【问题标题】:Invert dictionary with set of values from the original dict's values [duplicate]使用原始字典值中的一组值反转字典[重复]
【发布时间】:2016-07-12 15:20:10
【问题描述】:

我一直在尝试反转 Python 字典,即从原始字典中获取所有值,获取唯一集并将它们用作新字典的键。新键的值应该是原始 dict 的键的列表,它以新的 dict 键作为值。

当然有更好的方法,但我想出了:

myDict1 = {'foo0':'alpha','foo1':'alpha','bar0':'beta','bar4':'beta'}
tmpDict = dict.fromkeys(set(myDict1.values()),[])
for thingy in myDict1.keys():
    tmpDict[myDict1[thingy]].append(thingy)
print(tmpDict)

tmpDict 为:

{'alpha': ['bar0', 'foo0', 'foo1', 'bar4'], 'beta': ['bar0', 'foo0', 'foo1', 'bar4']}

这不是预期的字典:

{'alpha': ['foo0', 'foo1'], 'beta': ['bar0', 'bar4']}

哪里出错了?

【问题讨论】:

  • 你为什么有set(myDict1.keys())for thingy in myDict1 的行为相同。
  • 那个可能只是在试图让它工作和移动东西时的残余物 - 我看不出我现在添加它的原因。我已经编辑了这个问题。感谢您指出上一个问题!很高兴了解fromkeys() 等的引用行为!

标签: python dictionary set


【解决方案1】:

当你使用fromkeys 时,所有的键都指向同一个对象。在这种情况下是一个列表:

dict.fromkeys(set(myDict1.values()),[])

我建议使用:

dict((k, []) for k in set(myDict1.values()))

这将为每个键创建一个新列表。

【讨论】:

    猜你喜欢
    • 2020-11-28
    • 1970-01-01
    • 2021-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多