简体   繁体   English

在Python中嵌套字典中交换键顺序的有效方法是什么?

[英]What is an efficient way to exchange the order of keys in nested dictionaries in Python?

Apologies for the convoluted question title, but here's an example of what I mean. 对于令人困惑的问题标题表示歉意,但这是我的意思的示例。

Transform 转变

mydictionary = {"OuterKey1": {"InnerKey1": "Value1", "InnerKey2": "Value2"}, 
                "OuterKey2": {"InnerKey1": "Value3", "InnerKey2": "Value4"}}

into 进入

newdictionary = {"InnerKey1" : {"OuterKey1" : "Value1", "OuterKey2" : "Value3"},
                 "InnerKey2" : {"OuterKey1" : "Value2", "OuterKey2" : "Value4"}}

Notice how the association of InnerKey,OuterKey pair to values is preserved, but their order has simply been reversed. 请注意,如何保留InnerKey,OuterKey对与值的关联,但是它们的顺序只是颠倒了。 Where we would previously access Value1 using mydictionary[OuterKey][InnerKey] we now access it using newdictionary[InnerKey][OuterKey] . 在这里我们将以前访问Value1使用mydictionary[OuterKey][InnerKey]我们现在使用的访问newdictionary[InnerKey][OuterKey]

A direct way to achieve this would be to recreate two nested loops through the first dictionary and build the second dictionary one element at a time. 实现此目的的直接方法是通过第一个字典重新创建两个嵌套循环,并一次在一个元素上构建第二个字典。 However, I wonder if there's a cleaner / more Pythonic way to do it, such as with list comprehensions. 但是,我想知道是否有更干净/更Python化的方法来做到这一点,例如列表推导。

Update: It seems there is some confusion about the desired output. 更新:似乎对期望的输出有些困惑。 In particular, there is confusion about which value an OuterKey should map to after the tranformation. 特别是,在转换后,OuterKey应该映射到哪个值上会产生混淆。 The answer is that the former outer key (now inner key) should map to the same value that the former inner key (now outer key) mapped to. 答案是以前的外键(现在是内键)应该映射到与以前的内键(现在是外键)映射到的值相同的值。

In this case I find using setdefault in a loop (or a defaultdict ) much more readable then a comprehension. 在这种情况下,我发现在循环(或defaultdict )中使用setdefault可读性比理解的可读性高。 After all, "Readability counts...": 毕竟,“可读性很重要……”:

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'}}

The same using defaultdict : 使用defaultdict相同:

from collections import defaultdict
d = defaultdict(dict)
for k, v in mydictionary.items():
    for ik, iv in v.items():
            d[ik][k] = iv

Like this: 像这样:

>>> 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM