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

时间:2021-02-11 21:30:24

标签: python list dictionary zip

我有一本这样的字典:

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

上述方法有效,但我想知道是否有更优雅的 Pythonic 方法来做到这一点?

3 个答案:

答案 0 :(得分:2)

            $ExciterObject = New-Object PSObject
            $ExciterObject | Add-Member -MemberType NoteProperty -Name "Date Created" -Value $row.created_date
            $ExciterObject | Add-Member -MemberType NoteProperty -Name "Location" -Value $row.Location 
            $ExciterObject | Add-Member -MemberType NoteProperty -Name "Exciter Name" -Value $row.exciter_name 
            $ExciterObject | Add-Member -MemberType NoteProperty -Name "Exciter ID" -Value $row.ExciterID
            $ExciterObject | Add-Member -MemberType NoteProperty -Name "Reason Down" -Value $row.ReasonDown
            $exportObjectB += $ExciterObject

            }


$exportObjectA | ForEach-Object {
    if ($exportObjectB -contains $_) {
        Write-Host "`$exportObjectB contains the 
`$exportObjectA$row.exciter_name string [$_]"
    }

输出

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)

答案 1 :(得分:1)

我不明白输出列表中的外部dicts为什么不只是一个dict输出列表:

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

答案 2 :(得分:1)

这是使用列表推导和 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'}}]