我的字典具有这样的键值:
[{"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'}]
我被困在嵌入式循环中,但我不知道如何。
答案 0 :(得分:4)
您可以使用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)))
答案 1 :(得分:1)
如果您实际上总是只有"key1"
和"key2"
,那么:
In [1]: data = [{"key1" : ['1', '2'], "key2" : ['john', 'marvel']}, {"key1" : ['
...: 150', '120'], "key2" : ['gandalf', 'sam']}]
...:
In [2]: [{"key1":v1, "key2":v2} for d in data for (v1, v2) in zip(d['key1'], d['key2'])]
Out[2]:
[{'key1': '1', 'key2': 'john'},
{'key1': '2', 'key2': 'marvel'},
{'key1': '150', 'key2': 'gandalf'},
{'key1': '120', 'key2': 'sam'}]
会做
更通用的方法是:
In [5]: [dict(zip(d, vs)) for d in data for vs in zip(*d.values())]
Out[5]:
[{'key1': '1', 'key2': 'john'},
{'key1': '2', 'key2': 'marvel'},
{'key1': '150', 'key2': 'gandalf'},
{'key1': '120', 'key2': 'sam'}]
答案 2 :(得分:0)
result = [{}]
for item in data:
key, val = item.split(":", 1)
if key in result[-1]:
result.append({})
result[-1][key] = val
答案 3 :(得分:0)
在列表理解中具有2个循环的最简单方法
没有硬编码列表,也没有新变量
lst = [{"key1" : ['1', '2'], "key2" : ['john', 'marvel']}, {"key1" : ['150', '120'], "key2" : ['gandalf', 'sam']}]
[dict(zip(el.keys(), v)) for el in lst for k,v in el.items()]
[{'key1': '1', 'key2': '2'},
{'key1': 'john', 'key2': 'marvel'},
{'key1': '150', 'key2': '120'},
{'key1': 'gandalf', 'key2': 'sam'}]
答案 4 :(得分:0)
list1 = [ {'key1' : '1', 'key2' : 'john'}, {'key1' : '2', 'key2' : 'marvel'}, {'key1' : '150', 'key2' : 'gandalf'}, {'key1' : '120', 'key2' : 'sam'}]
list2 = [{'key1':i['key1'][0], 'key2':i['key2'][0]} for i in list1] + [{'key1':i['key1'][1], 'key2':i['key2'][1]} for i in list1]
list2
[{'key1': '1', 'key2': 'john'},
{'key1': '150', 'key2': 'gandalf'},
{'key1': '2', 'key2': 'marvel'},
{'key1': '120', 'key2': 'sam'}]