繁体   English   中英

将列表合并到字典列表中

[英]Merge lists into a list of dictionaries

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

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

我预期的 output 是这个,

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

实现这个 output 的最 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)
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = [5.0, 6.0, 7.0]
keys = ['key1', 'key2', 'key3']
lists = [list1, list2, list3]


result = []

for list in lists: 
    d = {}
    for i, j in zip(keys, list):
        d[i] = j
    result.append([d])

print(result)

在这个解决方案中,想法是通过以下方式将所有问题减少到只有一个字典: {key: array_to_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)

Output:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM