我有一个python字典,并希望在初始化dict时将其中一个值设置为键本身。那就是:
dummy = dict(
Key1 = ["SomeValue1", "Key1"],
Key2 = ["SomeValue2", "Key2"],
)
这可以通过程序化完成吗?也就是说,要再次跳过写入密钥并设置类似dummy.keys()[currentkeyindex]
的内容。
答案 0 :(得分:3)
>>> 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']]
})