python - 如何从具有相同值的多个字典中获取所有值到列表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)
输出:['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]
推荐阅读
- javascript - 获取捕获返回位置 0 处 JSON 中的意外令牌 U
- python - 由于 OperationalError,无法使用 teradataml 创建上下文
- r - R:替换两个数据框的数据并合并非相互数据
- python - 在 python 中读取 Bayer_rggb8 编码的原始视频的帧
- vb.net - 尽管测试成功,但表单身份验证失败
- bash - Bash循环不添加到数组
- c - 在 C 中编辑现有文件
- javascript - 从 PDF 中获取二进制数据(使用 JS),将其保存在 db 中并在 PHP 中取回
- python - 合并熊猫中的一列 - 只保留所有值的一行,而不是每个 matc 的新行
- android - 在 Service 和 Activity 中使用 RingtoneManager 的区别