[英]Converting dict of lists into list of dicts
I have a dictionary like so:我有一本像这样的字典:
{
"var1": [0, 1],
"var2": ["foo", "bar"]
}
Given the above, I want to end up with a list of dictionaries like so:鉴于上述情况,我想最终得到一个字典列表,如下所示:
[
{ "var1_0_var2_foo": {"var1": 0, "var2": "foo"} },
{ "var1_1_var2_bar": {"var1": 1, "var2": "bar"} }
]
The number of keys and elements in each list in the original dictionary is variable and can be anything.原始字典中每个列表中的键和元素的数量是可变的,可以是任何东西。
Here's my messy looking but working solution:这是我看起来凌乱但有效的解决方案:
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: 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'}}
]
The above works, but I was wondering if there's a better elegant pythonic way of doing this?以上工作,但我想知道是否有更好的优雅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 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'}}]
I don't understand what the reason for the outer dicts in the output list why not just a list of dict output:我不明白 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'}]
Here is a pythonic way to do this with list comprehension and lambda functions -这是使用列表理解和 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.