Python字典:将值设置为键字符串

时间:2014-12-31 02:29:16

标签: python dictionary

我有一个python字典,并希望在初始化dict时将其中一个值设置为键本身。那就是:

dummy = dict(
  Key1 = ["SomeValue1", "Key1"],
  Key2 = ["SomeValue2", "Key2"],
  )

这可以通过程序化完成吗?也就是说,要再次跳过写入密钥并设置类似dummy.keys()[currentkeyindex]的内容。

2 个答案:

答案 0 :(得分:3)

使用dict comprehension

>>> values = [
...     ["SomeValue1", "Key1"],
...     ["SomeValue2", "Key2"],
... ]
>>> {x[1]: x for x in values}
{'Key2': ['SomeValue2', 'Key2'], 'Key1': ['SomeValue1', 'Key1']}

答案 1 :(得分:3)

如果您想跟踪项目,请使用defaultdict

>>> from collections import defaultdict                                                                                                      
>>> output = defaultdict(list)
>>> values = [
        ["SomeValue1", "Key1"],
        ["SomeValue2a", "Key2"],
        ["SomeValue2b", "Key2"]
    ]
>>> for x in values:
...     output[x[1]].append(x)
... 
>>> output
defaultdict(<type 'list'>, {
    'Key2': [['SomeValue2a', 'Key2'], ['SomeValue2b', 'Key2']], 
    'Key1': [['SomeValue1', 'Key1']]
})