python - 将对象列表转换为列表字典

标签 python python-3.x list-comprehension dictionary-comprehension

我有一个 JSON 对象列表,已经排序(比如说按时间排序)。每个 JSON 对象都有 typestatus。例如:

[
    {'type': 'A', 'status': 'ok'},
    {'type': 'B', 'status': 'ok'},
    {'type': 'A', 'status': 'fail'}
]

我想将其转换为:

{
    'A': ['ok', 'fail'],
    'B': ['ok']
}

当然,这是一项简单的任务,但我正在寻找 Pythonic 的方式来做到这一点,这样我就可以节省几行代码

最佳答案

我不知道是否有单行,但你可以使用setdefaultdefaultdict达到预期的结果:

data = [
    {'type': 'A', 'status': 'ok'},
    {'type': 'B', 'status': 'ok'},
    {'type': 'A', 'status': 'fail'}
]

使用setdefault():

res = {}
for elt in data:
    res.setdefault(elt['type'], []).append(elt['status'])

输出:

{'A': ['ok', 'fail'], 'B': ['ok']}

使用defaultdict:

from collections import defaultdict
res = defaultdict(list)
for elt in data:
    res[elt['type']].append(elt['status'])

输出:

defaultdict(<class 'list'>, {'A': ['ok', 'fail'], 'B': ['ok']})

关于python - 将对象列表转换为列表字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66901136/

相关文章:

python - 创建依赖于另一个变量的变量

python - 在数据帧中查找第一个匹配对并标记两者

python - 列表理解 : create 2 items for each item in input list?

python - 尝试,除了 ValueError 替换为 None

python - Python 2.7 中使用列表理解的多个 with 语句

Python 3.x - 如何有效地将对象数组拆分为更小的批处理文件?

python - 打开具有多个空格的文件并保存为具有两个变量的数组/数据框

javascript - 在 Flask 中使用 make_response 将两个变量传递给 javascript

python - 内存溢出(?)在 tkinter 上崩溃

python - 检查元素是否存在,如果不存在则执行 ..