python - 将值列表拆分为字典列表

标签 python

我有这样的键值字典:

[{"key1" : ['1', '2'], "key2" : ['john', 'marvel']}, {"key1" : ['150', '120'], "key2" : ['gandalf', 'sam']}]

我想得到这样的东西:

[ {key1 : '1', key2 : 'john'}, {key1 : '2', key2 : 'marvel'}, {key1 : '150', key2 : 'gandalf'}, {key1 : '120', key2 : 'sam'}]

我被卡住了,我想嵌入循环,但我不知道怎么做。

最佳答案

你可以使用 list comprehension :

data = [{"key1": ['1', '2'], "key2": ['john', 'marvel']}, {"key1": ['150', '120'], "key2": ['gandalf', 'sam']}]

keys = ['key1', 'key2']
result = [dict(zip(keys, items)) for d in data for items in zip(*(d[k] for k in keys))]

print(result)

输出

[{'key2': 'john', 'key1': '1'}, {'key2': 'marvel', 'key1': '2'}, {'key2': 'gandalf', 'key1': '150'}, {'key2': 'sam', 'key1': '120'}]

上面的列表理解等价于下面的for循环:

result = []
for d in data:
    for items in zip(*(d[k] for k in keys)):
        result.append(dict(zip(keys, items)))

关于python - 将值列表拆分为字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53957185/

相关文章:

python - 添加到布局的 PyQt4 自定义小部件(已加载 uic)是不可见的

python - 从 python 中已打开的文件中读取两种换行符类型

python - 检测 Python 代码在哪里运行(例如,在 Spyder 解释器、IDLE 和 cmd 中)

python - Ubuntu16.04下virtualenv中psutil的安装

python - Paramiko 在 psql 上执行命令

python - 简单 HTTP 服务器 SSL record_too_long 错误

python - 关于注册表中不存在的连接名称的 CQL 引擎异常

python - Pandas to_html 不显示附加数据

python - 在 python 中的第 n 个字节之后追加到文件

python - 在numpy数组中查找大量满足条件的连续值