Python how to convert a list of dict to a list of tuples

穿精又带淫゛_ 提交于 2020-01-23 08:16:40

问题


I have a list of dict that looks like this:

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.

Is there anybody whom can help me?


回答1:


You can use list comprehension for that:

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

Here we iterate over all dictonaries in list. For every dictionary we iterate over its .items() and extract the key and value and then we construct a tuple for that with (key,)+val.

Whether the values are strings or not is irrelevant: the list comprehension simply copies the reference so if the original elements were Foos, they remain Foos.

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. But the order of tuples for each individual dictionary is not determined.




回答2:


List-comprehension one-liner for 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.

For older versions of Python see answer by @WillemVanOnsem which does not make use of the starred expressions (*v).




回答3:


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



回答4:


If your values in the dictionary are always lists of length 2, you could do:

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



回答5:


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:

>>> 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.

Please let me know if any of my assumptions are incorrect.



来源:https://stackoverflow.com/questions/42249655/python-how-to-convert-a-list-of-dict-to-a-list-of-tuples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!