![](/img/trans.png)
[英]What is the most efficient way to create nested dictionaries in Python?
[英]What is an efficient way to exchange the order of keys in nested dictionaries in Python?
对于令人困惑的问题标题表示歉意,但这是我的意思的示例。
转变
mydictionary = {"OuterKey1": {"InnerKey1": "Value1", "InnerKey2": "Value2"},
"OuterKey2": {"InnerKey1": "Value3", "InnerKey2": "Value4"}}
进入
newdictionary = {"InnerKey1" : {"OuterKey1" : "Value1", "OuterKey2" : "Value3"},
"InnerKey2" : {"OuterKey1" : "Value2", "OuterKey2" : "Value4"}}
请注意,如何保留InnerKey,OuterKey
对与值的关联,但是它们的顺序只是颠倒了。 在这里我们将以前访问Value1
使用mydictionary[OuterKey][InnerKey]
我们现在使用的访问newdictionary[InnerKey][OuterKey]
实现此目的的直接方法是通过第一个字典重新创建两个嵌套循环,并一次在一个元素上构建第二个字典。 但是,我想知道是否有更干净/更Python化的方法来做到这一点,例如列表推导。
更新:似乎对期望的输出有些困惑。 特别是,在转换后,OuterKey应该映射到哪个值上会产生混淆。 答案是以前的外键(现在是内键)应该映射到与以前的内键(现在是外键)映射到的值相同的值。
在这种情况下,我发现在循环(或defaultdict
)中使用setdefault
可读性比理解的可读性高。 毕竟,“可读性很重要……”:
mydictionary = {"OuterKey1": {"InnerKey1": "Value1", "InnerKey2": "Value2"}, "OuterKey2": {"InnerKey1": "Value3", "InnerKey2": "Value4"}}
d = {}
for k, v in mydictionary.items():
for ik, iv in v.items():
d.setdefault(ik, {})[k] = iv
# result:
# d == {'InnerKey2': {'OuterKey2': 'Value4', 'OuterKey1': 'Value2'}, 'InnerKey1': {'OuterKey2': 'Value3', 'OuterKey1': 'Value1'}}
使用defaultdict
相同:
from collections import defaultdict
d = defaultdict(dict)
for k, v in mydictionary.items():
for ik, iv in v.items():
d[ik][k] = iv
像这样:
>>> mydictionary = {"OuterKey1": {"InnerKey1": "Value1", "InnerKey2": "Value2"},
... "OuterKey2": {"InnerKey1": "Value3", "InnerKey2": "Value4"}}
>>> dict([(k, dict([(k2,mydictionary[k2][k]) for k2 in mydictionary]))
... for k in mydictionary.values()[0]])
{'InnerKey2': {'OuterKey2': 'Value4', 'OuterKey1': 'Value2'},
'InnerKey1': {'OuterKey2': 'Value3', 'OuterKey1': 'Value1'}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.