繁体   English   中英

Python如何将dict列表转换为元组列表

[英]Python how to convert a list of dict to a list of tuples

我有一个dict列表,如下所示:

list=[{u'hello':['001', 3], u'word':['003', 1], u'boy':['002', 2]}, 
     {u'dad':['007', 3], u'mom':['005', 3], u'honey':['002', 2]} ] 

我需要的是迭代我的列表,以创建这样的元组列表:

new_list=[('hello','001', 3), ('word','003',1), ('boy','002', 2)
           ('dad','007',3), ('mom', '005', 3), ('honey','002',2)]

注意! 零('001',003'等等)的数字必须考虑为字符串。

有没有人可以帮助我?

你可以使用list comprehension:

new_list = [(key,)+tuple(val) for dic in list for key,val in dic.items()]

在这里,我们迭代in list所有dic tonaries。 对于每一个dic我们遍历其tionary .items()并提取keyval UE,然后我们构建了一个元组与(key,)+val

值是否为字符串是无关紧要的:列表推导只是复制引用,所以如果原始元素是Foo ,它们仍然是Foo

最后请注意,词典是无序的,所以顺序是不确定的。 但是,如果字典d1出现在字典d2之前,则第一个元素的所有元素将被放置在后者的元组之前的列表中。 但是没有确定每个单独字典的元组顺序。

Python 3.5+的列表理解单行:

my_list=[{u'hello':['001', 3], u'word':['003', 1], u'boy':['002', 2]},
         {u'dad':['007', 3], u'mom':['005', 3], u'honey':['002', 2]}]

result = [(k, *v) for f in my_list for k,v in f.items()]

# [('word', '003', 1), ('hello', '001', 3), ('boy', '002', 2), ('dad', '007', 3), ('honey', '002', 2), ('mom', '005', 3)]

PS:不要使用变量名称list因为它是内置的python。

对于旧版本的Python,请参阅@WillemVanOnsem的答案,该答案不使用已加星标的表达式( *v )。

list=[{u'hello':['001', 3], u'word':['003', 1], u'boy':['002', 2]}, 
     {u'dad':['007', 3], u'mom':['005', 3], u'honey':['002', 2]} ] 

 >>> [map(lambda (k,v): (k,)+tuple(v), dictionary.iteritems()) for dictionary in list]

[[(u'boy', '002', 2), (u'word', '003', 1), (u'hello', '001', 3)], [(u'dad', '007', 3), (u'honey', '002', 2), (
u'mom', '005', 3)]]
>>>

如果字典中的值始终是长度为2的列表,则可以执行以下操作:

new_list = [ (key, value[0], value[1]) for dict in list for key, value in dict.iteritems() ]

假设您不关心将输出重新编码为ASCII,如您的示例所示,您不关心保留顺序,并且您希望合并项目以防它们在列出的联合中出现多次字典,这个代码示例应该工作:

>>> input_list = [
...    {u'hello': ['001', 3], u'word': ['003', 1], u'boy': ['002', 2]},
...    {u'dad': ['007', 3], u'mom': ['005', 3], u'honey': ['002', 2]}] 
...
>>> temporary_dict = {}
>>> output_list = []
>>> for dictionary in input_list:
...     for key in dictionary.keys():
...         if key in temporary_dict:
...             temporary_dict[key] += dictionary[key]
...         else:
...             temporary_dict[key] = dictionary[key]
...
>>> for key in temporary_dict.keys():
...     output_list.append(tuple([key] + temporary_dict[key]))
...
>>> print(output_list)
[(u'dad', '007', 3), (u'boy', '002', 2), (u'word', '003', 1),
 (u'honey', '002', 2), (u'mom', '005', 3), (u'hello', '001', 3)]

请注意我如何首先将所有列出的字典中的键连接到一个temporary_dict ,然后迭代该字典,创建字典key的连接列表以及该键的值( temporary_dict[key] ),并将它们附加到新的输出清单。

如果我的任何假设不正确,请告诉我。

暂无
暂无

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

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