Skip to main content
 首页 » 编程设计

python之将值列表拆分为字典列表

2025年05月04日20dyllove98

我有这样的键值字典:

[{"key1" : ['1', '2'], "key2" : ['john', 'marvel']}, {"key1" : ['150', '120'], "key2" : ['gandalf', 'sam']}] 

我想得到这样的东西:

[ {key1 : '1', key2 : 'john'}, {key1 : '2', key2 : 'marvel'}, {key1 : '150', key2 : 'gandalf'}, {key1 : '120', key2 : 'sam'}] 

我被卡住了,我想嵌入循环,但我不知道怎么做。

请您参考如下方法:

你可以使用 list comprehension :

data = [{"key1": ['1', '2'], "key2": ['john', 'marvel']}, {"key1": ['150', '120'], "key2": ['gandalf', 'sam']}] 
 
keys = ['key1', 'key2'] 
result = [dict(zip(keys, items)) for d in data for items in zip(*(d[k] for k in keys))] 
 
print(result) 

输出

[{'key2': 'john', 'key1': '1'}, {'key2': 'marvel', 'key1': '2'}, {'key2': 'gandalf', 'key1': '150'}, {'key2': 'sam', 'key1': '120'}] 

上面的列表理解等价于下面的for循环:

result = [] 
for d in data: 
    for items in zip(*(d[k] for k in keys)): 
        result.append(dict(zip(keys, items)))