簡體   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