简体   繁体   English

创建一个具有唯一键和来自元组的各种列表值的字典

[英]create a dict with unique keys and various list values from a tuple

I have a list of tuples like this one:我有一个像这样的元组列表:

[('id1', 'text1', 0, 'info1'),
 ('id2', 'text2', 1, 'info2'),
 ('id3', 'text3', 1, 'info3'),
 ('id1', 'text4', 0, 'info4'),
 ('id4', 'text5', 1, 'info5'),
 ('id3', 'text6', 0, 'info6')]

I want to convert it to dict, keeping the ids as keys and all other values as lists of tuples, expanding the ones that aready exist:我想将其转换为 dict,将 ids 保留为键,将所有其他值保留为元组列表,扩展存在的那些:

{'id1': [('text1', 0, 'info1'),
         ('text4', 0, 'info4')],
 'id2': [('text2', 1, 'info2')],
 'id3': [('text3', 1, 'info3'),
         ('text6', 0, 'info6')],
 'id4': [('text5', 1, 'info5')]}

Right now I use the pretty simple code:现在我使用非常简单的代码:

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]))

I beleive there should be more elegant way to achieve the same result, with generators maybe.我相信应该有更优雅的方式来实现相同的结果,也许使用生成器。 Any ideas?有任何想法吗?

A useful method for appending to lists contained in a dictionary for these kind of problems isdict.setdefault .将此类问题附加到包含在字典中的列表的一种有用方法是dict.setdefault You can use it to retrieve an existing list from a dictionary, or add an empty one if it is missing, like so:您可以使用它从字典中检索现有列表,或者在缺少时添加一个空列表,如下所示:

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:])

Result:结果:

{'id1': [('text1', 0, 'info1'), ('text4', 0, 'info4')],
 'id2': [('text2', 1, 'info2')],
 'id3': [('text3', 1, 'info3'), ('text6', 0, 'info6')],
 'id4': [('text5', 1, 'info5')]}

I actually find the setdefault method a bit awkward to use (and some people agree ), and always forget how it works exactly.我实际上发现setdefault方法使用起来有点尴尬(有些人也同意),并且总是忘记它是如何工作的。 I usually use collections.defaultdict instead:我通常使用collections.defaultdict代替:

from collections import defaultdict
x = defaultdict(list)
for tup in data:
    x[tup[0]].append(tup[1:])

which has similar results.这有类似的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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