将列表的字典转换为字典的列表



我有一个这样的字典:

{
"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)

输出:

[
{'x_a_y_0_z_foo': {'x': 'a', 'y': 0, 'z': 'foo'}}, 
{'x_b_y_1_z_bar': {'x': 'b', 'y': 1, 'z': 'bar'}}
]

上面的工作,但我想知道是否有一个更好的优雅的python方式做到这一点?

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)

输出
[{'x_a_y_0_z_foo': {'x': 'a', 'y': 0, 'z': 'foo'}},
{'x_b_y_1_z_bar': {'x': 'b', 'y': 1, 'z': 'bar'}}]

下面是使用列表推导式和lambda函数来完成此操作的python方法-

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'}}]

我不明白输出列表中外部字典的原因,为什么不只是一个字典输出列表:

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'}]

相关内容

  • 没有找到相关文章

最新更新