[英]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.