嵌套字典的元组列表,不覆盖 [英] List of tuples to nested dictionary without overriding
本文介绍了嵌套字典的元组列表,不覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将上述元组列表转换为嵌套字典,而不会覆盖python中的以下值
I need to convert the above list of tuples to nested dictionary without overwriting the value as below in python
[('a', '1'),
('b', 'true'),
('b', 'none'),
('a', '2'),
('b', 'true'),
('a', '3'),
('b', 'false')]
{'a': {'1' : { 'b' : ('true','none')},
'2' : { 'b' : ('true')},
'3' : { 'b' : ('false')}}}
使用
dict()
和合并字典不起作用.有什么pythonic的方法可以做到这一点吗?
and merging the dictionary doesn't work. Is there any pythonic way to do this?
推荐答案
这是使用您还可以使用字典的setdefault
方法返回新键的默认值,尽管defaultdict
方法更简洁,更快捷:
You could also use the dictionary's setdefault
method to return default values for new keys, although the defaultdict
approach is much cleaner and faster:
c = {}
for i, j in data:
if i == 'a':
q = c.setdefault(i, {}).setdefault(j, {})
else:
q[i] = q.setdefault(i, ()) + (j,)
pprint.pprint(c)
# {'a': {'1': {'b': ('true', 'none')},
# '2': {'b': ('true',)},
# '3': {'b': ('false',)}}}
这篇关于嵌套字典的元组列表,不覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文