首页 > 解决方案 > 如何从具有相同值的多个字典中获取所有值到列表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'}]

谁能帮我

标签: python

解决方案


各位,请正确阅读问题。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)

输出:['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]

推荐阅读