我有一个包含以下数据的列表second_list
:
{"forename":"SomeForename","surname":"SomeSurname","title":"MR"}
{"postTown":"LONDON"}
{"country":"ZIMBABWE"}
{"forename":"SomeOtherForename","surname":"SomeOtherSurname"}
{"postTown":"LONDON"}
{"country":"ZIMBABWE"}
我试图将该列表转换为这样的字典:
dict_values = {}
for i in second_list:
dict_values.update(ast.literal_eval(i))
但字典的键和值会被最后一个键和值覆盖。所以,我得到一个包含以下数据的字典:
{"forename":"SomeOtherForename","surname":"SomeOtherSurname"}
{"postTown":"LONDON"}
{"country":"ZIMBABWE"}
我想要实现的是将包含list的字典作为这样的值:
{'forename':[someForename, SomeOtherForename], 'surname:'[someSurname, someOtherSurname]}
等
有没有办法将所有数据从列表转换为字典而不会覆盖它?
答案 0 :(得分:2)
from collections import defaultdict
dict_values = defaultdict(list)
for i in second_list:
for k, v in ast.literal_eval(i).iteritems():
dict_values[k].append(v)