[英]Converting dict of lists into list of dicts
我有一本像這樣的字典:
{
"var1": [0, 1],
"var2": ["foo", "bar"]
}
鑒於上述情況,我想最終得到一個字典列表,如下所示:
[
{ "var1_0_var2_foo": {"var1": 0, "var2": "foo"} },
{ "var1_1_var2_bar": {"var1": 1, "var2": "bar"} }
]
原始字典中每個列表中的鍵和元素的數量是可變的,可以是任何東西。
這是我看起來凌亂但有效的解決方案:
source = {
'x': ['a', 'b'],
'y': [0, 1],
'z': ['foo', 'bar']
}
target = []
names = list(source.keys())
lists = list(source.values())
zipped = list(zip(*lists))
for item in zipped:
full_name = ""
full_dict = {}
for idx, value in enumerate(item):
full_name += f"{names[idx]}_{value}_"
full_dict[names[idx]] = value
full_name = full_name.rstrip('_')
target.append({full_name: full_dict})
print(target)
Output:
[
{'x_a_y_0_z_foo': {'x': 'a', 'y': 0, 'z': 'foo'}},
{'x_b_y_1_z_bar': {'x': 'b', 'y': 1, 'z': 'bar'}}
]
以上工作,但我想知道是否有更好的優雅pythonic方式來做到這一點?
from itertools import chain
spam = {'x': ['a', 'b'],
'y': [0, 1],
'z': ['foo', 'bar']}
eggs = []
for item in zip(*spam.values()):
key = '_'.join(chain(*zip(spam.keys(), map(str, item))))
eggs.append({key:dict(zip(spam.keys(), item))})
print(eggs)
output
[{'x_a_y_0_z_foo': {'x': 'a', 'y': 0, 'z': 'foo'}},
{'x_b_y_1_z_bar': {'x': 'b', 'y': 1, 'z': 'bar'}}]
我不明白 output 列表中的外部字典的原因是什么,為什么不只是字典 output 的列表:
data = {
'var1': [0, 1],
'var2': ["foo", "bar"]}
output = [dict(zip(data, vars)) for vars in zip(*data.values())]
[{'var1': 0, 'var2': 'foo'}, {'var1': 1, 'var2': 'bar'}]
這是使用列表理解和 lambda 函數執行此操作的 pythonic 方法 -
d = {
'x': ['a', 'b'],
'y': [0, 1],
'z': ['foo', 'bar']
}
f = lambda x: {i:j for i,j in zip(d,x)} #Creates the values of final output
g = lambda x: '_'.join([str(j) for i in zip(d,x) for j in i]) #Creates the keys of final output
target = [{g(i):f(i)} for i in zip(*d.values())]
print(target)
[{'x_a_y_0_z_foo': {'x': 'a', 'y': 0, 'z': 'foo'}},
{'x_b_y_1_z_bar': {'x': 'b', 'y': 1, 'z': 'bar'}}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.