完全是一个编程新手,需要一些帮助
我所拥有的是以下格式的词典列表:
a_list = [
{'ID': 'a', 'Animal': 'dog', 'color': 'white', 'tail': 'yes'},
{'ID': 'a', 'Animal': 'cat', 'color': 'black', 'tail': 'yes'},
{'ID': 'b', 'Animal': 'bird', 'color': 'black', 'tail': 'no'},
{'ID': 'b', 'Animal': 'cat', 'color': 'pink', 'tail': 'yes'}
{'ID': 'b', 'Animal': 'dog', 'color': 'yellow', 'tail': 'no'}
]
我想要的是一本词典,如下所示:
a_dict =
{'a': {'dog': {'color': 'white', 'tail': 'yes'},
'cat': {'color': 'black', 'tail': 'yes'}},
'b': {'bird': {'color': 'black', 'tail': 'no'},
'cat': {'color': 'pink', 'tail': 'no'},
'dog': {'color': 'yellow', 'tail': 'no'}}}
印刷品:
使用
defaultdict
的简单解决方案创建了一个嵌套字典并删除了以后不需要的所有键
输出:
相关问题 更多 >
编程相关推荐