[英]Create a JSON dict from a list of values from a tuple and a separate list of keys
[英]create a dict with unique keys and various list values from a tuple
我有一个像这样的元组列表:
[('id1', 'text1', 0, 'info1'),
('id2', 'text2', 1, 'info2'),
('id3', 'text3', 1, 'info3'),
('id1', 'text4', 0, 'info4'),
('id4', 'text5', 1, 'info5'),
('id3', 'text6', 0, 'info6')]
我想将其转换为 dict,将 ids 保留为键,将所有其他值保留为元组列表,扩展存在的那些:
{'id1': [('text1', 0, 'info1'),
('text4', 0, 'info4')],
'id2': [('text2', 1, 'info2')],
'id3': [('text3', 1, 'info3'),
('text6', 0, 'info6')],
'id4': [('text5', 1, 'info5')]}
现在我使用非常简单的代码:
for x in list:
if x[0] not in list: list[x[0]] = [(x[1], x[2], x[3])]
else: list[x[0]].append((x[1], x[2], x[3]))
我相信应该有更优雅的方式来实现相同的结果,也许使用生成器。 有任何想法吗?
将此类问题附加到包含在字典中的列表的一种有用方法是dict.setdefault 。 您可以使用它从字典中检索现有列表,或者在缺少时添加一个空列表,如下所示:
data = [('id1', 'text1', 0, 'info1'),
('id2', 'text2', 1, 'info2'),
('id3', 'text3', 1, 'info3'),
('id1', 'text4', 0, 'info4'),
('id4', 'text5', 1, 'info5'),
('id3', 'text6', 0, 'info6')]
x = {}
for tup in data:
x.setdefault(tup[0], []).append(tup[1:])
结果:
{'id1': [('text1', 0, 'info1'), ('text4', 0, 'info4')],
'id2': [('text2', 1, 'info2')],
'id3': [('text3', 1, 'info3'), ('text6', 0, 'info6')],
'id4': [('text5', 1, 'info5')]}
我实际上发现setdefault
方法使用起来有点尴尬(有些人也同意),并且总是忘记它是如何工作的。 我通常使用collections.defaultdict代替:
from collections import defaultdict
x = defaultdict(list)
for tup in data:
x[tup[0]].append(tup[1:])
这有类似的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.