python - 将列表合并到字典列表中

标签 python list dictionary

我有三个列表和每个列表的三个键,并且想将它们转换为字典列表。

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = [5.0, 6.0, 7.0]
keys = ['key1', 'key2', 'key3']

我的预期输出是这样的,

[[{'key1': 1, 'key2': 'a', 'key3': 5.0}], 
 [{'key1': 2, 'key2': 'b', 'key3': 6.0}], 
 [{'key1': 3, 'key2': 'c', 'key3': 7.0}]]

实现此输出的最 Pythonic 方法是什么?

最佳答案

尝试:

list1 = [1, 2, 3]
list2 = ["a", "b", "c"]
list3 = [5.0, 6.0, 7.0]
keys = ["key1", "key2", "key3"]

out = []
for t in zip(list1, list2, list3):
    out.append([dict(zip(keys, t))])

print(out)

打印:

[[{'key1': 1, 'key2': 'a', 'key3': 5.0}], 
 [{'key1': 2, 'key2': 'b', 'key3': 6.0}], 
 [{'key1': 3, 'key2': 'c', 'key3': 7.0}]]

或者:

out = [[dict(zip(keys, t))] for t in zip(list1, list2, list3)]
print(out)

关于python - 将列表合并到字典列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67895788/

相关文章:

java - java TreeMap中的树是什么意思?

javascript - 字典:JavaScript 中的映射与对象

python - 使用python限制类实例的数量

python - Django 在 url 中传递一个字符串

list - Flutter 上传列表到 Google Firestore

python - 如何根据列表中的值在字典列表中查找字典?

python-3.x - 重写的 __setitem__ 调用以串行方式工作,但在 apply_async 调用中中断

python - 修改 Python 列表的每个元素并将结果组合成一个字符串

Python - 正确提取拆分列表

java - 在java中合并json对象