簡體   English   中英

如何從具有相同值的多個字典中獲取所有值到列表 python

[英]How to get all value from multiple dictionary with same value into list python

我想制作如下列表

data2 = ['Run, Read', 'Sing, Read', 'Run, Sing, Read', 'Read']

從這個列表

data = [
{29: 'Run'}, 
{29: 'Read'}, 
{30: 'Sing'}, 
{30: 'Read'}, 
{31: 'Run'}, 
{31: 'Sing'}, 
{31: 'Read'}, 
{32: 'Read'}]

誰能幫我

各位,請正確閱讀問題。 OP 正在詢問如何將具有相同鍵的不同字典的字符串收集到單個字符串中。

我有點想知道你最終會如何得到一個這樣的字典列表,而不是像

data = [
{29: 'Run', 30: 'Sing', 31: 'Read', 32: 'Read'}, 
{29: 'Read', 30: 'Read', 31: 'Run'},
{31: 'Sing')] 

這基本上是相同的,但除此之外。

您可以使用以下內容輕松地做您想做的事情:

data = [
{29: 'Run'}, 
{29: 'Read'}, 
{30: 'Sing'}, 
{30: 'Read'}, 
{31: 'Run'}, 
{31: 'Sing'}, 
{31: 'Read'}, 
{32: 'Read'}]

# Create empty dict for all keys
key_dct = {}

# Loop over all dicts in the list
for dct in data:
    # Loop over every item in this dict
    for key, value in dct.items():
        # Add value to the dict with this key
        key_dct.setdefault(key, []).append(value)

# Combine all items in key_dct into strings
data2 = [', '.join(value) for value in key_dct.values()]

# Print data2
print(data2)

Output: ['Run, Read', 'Sing, Read', 'Run, Sing, Read', 'Read']

請注意,即使某些字典包含多個項目,我的解決方案也有效。

編輯:如果您想確定字符串的順序也是鍵的數字順序,則將上面代碼段中data2的創建替換為

# Sort items on their key values
items = list(key_dct.items())
items.sort(key=lambda x: x[0])

# Combine all items into strings
data2 = [', '.join(value) for _, value in items]

您可以使用collections.defaultdict將相同的鍵值放入列表中,然后連接這些值。

from collections import defaultdict

result = defaultdict(list)
for d in data:
    for k, v in d.items():
        result[k].append(v)

result = [", ".join(value) for _, value in result.items()]

print(result)

Output:

['Run, Read', 'Sing, Read', 'Run, Sing, Read', 'Read']

你的意思是像:

data2 = [list(d.values())[0] for d in data]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM