嵌套字典的键交换

2024-04-25 13:30:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典如下:

每个键都有一个与其相关联的字典。你知道吗

dict_sample = {'a': {'d0': '1', 'd1': '2', 'd2': '3'}, 'b': {'d0': '1'}, 'c': {'d1': '1'}}

我需要如下输出:

output_dict = {'d0': {'a': 1, 'b': 1}, 'd1': {'a': 2, 'c': 1}, 'd2': {'a': 3}}

我很感激任何帮助在Python的方式来实现这一点。谢谢您!你知道吗


Tags: sampleoutput字典方式dictd2d1d0
2条回答

您可以在具有嵌套循环的新dict上使用dict.setdefault

d = {}
# for each key and sub-dict in the main dict
for k1, s in dict_sample.items():
    # for each key and value in the sub-dict
    for k2, v in s.items():
        # this is equivalent to d[k2][k1] = int(v), except that when k2 is not yet in d,
        # setdefault will initialize d[k2] with {} (a new dict)
        d.setdefault(k2, {})[k1] = int(v)

d将变成:

{'d0': {'a': 1, 'b': 1}, 'd1': {'a': 2, 'c': 1}, 'd2': {'a': 3}}

我相信这会产生预期的结果

>>> from collections import defaultdict
>>> d = defaultdict(dict)
>>>
>>> dict_sample = {'a': {'d0': '1', 'd1': '2', 'd2': '3'}, 'b': {'d0': '1'}, 'c': {'d1': '1'}}
>>>
>>> for key, value in dict_sample.items():
...     for k, v in value.items():
...         d[k][key] = v
...
>>> d
defaultdict(<class 'dict'>, {'d0': {'a': '1', 'b': '1'}, 'd1': {'a': '2', 'c': '1'}, 'd2': {'a': '3'}})

相关问题 更多 >

    热门问题