我有这样的键值字典:
[{"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)))
关于python - 将值列表拆分为字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53957185/