Python 将列表合并到词典列表中
我有三个列表,每个列表有三个键,我想把它们转换成字典列表Python 将列表合并到词典列表中,python,list,dictionary,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', '
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}]]
实现这一输出的最佳方式是什么?试试:
list1=[1,2,3]
清单2=[“a”、“b”、“c”]
清单3=[5.0,6.0,7.0]
键=[“键1”、“键2”、“键3”]
out=[]
对于zip中的t(列表1、列表2、列表3):
out.append([dict(zip(key,t))]))
打印(输出)
印刷品:
[{'key1':1,'key2':'a','key3':5.0}],
[{'key1':2,'key2':'b','key3':6.0}],
[{'key1':3,'key2':'c','key3':7.0}]
或:
out=[[dict(zip(key,t))]表示zip中的t(list1,list2,list3)]
打印(输出)
在这个解决方案中,想法是通过以下方式将所有问题简化为一个字典:{key:array\u to\u assign}
from functools import reduce
from collections import OrderedDict
list_response = []
list_dicts = []
list_values = [list1, list2, list3]
for index, k in enumerate(keys):
list_dicts.append(
OrderedDict({k: list_values[index]})
)
my_dictionary = reduce(lambda d1, d2: OrderedDict(list(d1.items()) + list(d2.items())) , list_dicts)
最后,我们迭代字典并将嵌套列表的项分配给正确的键
for key, value in my_dictionary.items():
for i in value:
list_response.append({
key: i
})
print(list_response)
输出:
[
{'key1': 1},
{'key1': 2},
{'key1': 3},
{'key2': 'a'},
{'key2': 'b'},
{'key2': 'c'},
{'key3': 5.0},
{'key3': 6.0},
{'key3': 7.0}
]
虽然此代码可能会回答该问题,但提供有关此代码为什么和/或如何回答该问题的附加上下文可提高其长期价值。
[
{'key1': 1},
{'key1': 2},
{'key1': 3},
{'key2': 'a'},
{'key2': 'b'},
{'key2': 'c'},
{'key3': 5.0},
{'key3': 6.0},
{'key3': 7.0}
]