简体   繁体   English

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

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

I have a list of dict that looks like this: 我有一个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]} ] 

What I need is to iterate on my list in order to create list of tuples like this: 我需要的是迭代我的列表,以创建这样的元组列表:

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

NOTE! 注意! the numbers with the zeros ('001',003'... and so on) must be considerated as a string. 零('001',003'等等)的数字必须考虑为字符串。

Is there anybody whom can help me? 有没有人可以帮助我?

You can use list comprehension for that: 你可以使用list comprehension:

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

Here we iterate over all dic tonaries in list . 在这里,我们迭代in list所有dic tonaries。 For every dic tionary we iterate over its .items() and extract the key and val ue and then we construct a tuple for that with (key,)+val . 对于每一个dic我们遍历其tionary .items()并提取keyval UE,然后我们构建了一个元组与(key,)+val

Whether the values are strings or not is irrelevant: the list comprehension simply copies the reference so if the original elements were Foo s, they remain Foo s. 值是否为字符串是无关紧要的:列表推导只是复制引用,所以如果原始元素是Foo ,它们仍然是Foo

Finally note that the dictionaries are unordered, so the order is undetermined. 最后请注意,词典是无序的,所以顺序是不确定的。 However if a dictionary d1 occurs before a dictionary d2 , all the elements of the first will be placed in the list before the tuples of the latter. 但是,如果字典d1出现在字典d2之前,则第一个元素的所有元素将被放置在后者的元组之前的列表中。 But the order of tuples for each individual dictionary is not determined. 但是没有确定每个单独字典的元组顺序。

List-comprehension one-liner for Python 3.5+ : 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: Do not use the variable name list since it is a python built-in. PS:不要使用变量名称list因为它是内置的python。

For older versions of Python see answer by @WillemVanOnsem which does not make use of the starred expressions ( *v ). 对于旧版本的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() ]

Assuming that you don't care about having the output re-coded as ASCII as your example shows, that you don't care about preserving order and that you want to merge items in case they appear more than once across the union of the listed dictionaries, this code example should work: 假设您不关心将输出重新编码为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)]

Note how I first concatenate the keys from all of the listed dictionaries into a temporary_dict and then I iterate over that dictionary, making a concatenated list of the dictionary key as well as that key's values ( temporary_dict[key] ), and append them to a new output list. 请注意我如何首先将所有列出的字典中的键连接到一个temporary_dict ,然后迭代该字典,创建字典key的连接列表以及该键的值( temporary_dict[key] ),并将它们附加到新的输出清单。

Please let me know if any of my assumptions are incorrect. 如果我的任何假设不正确,请告诉我。

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

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