Python从具有键:值字符串的列表创建字典

时间:2016-12-07 12:16:24

标签: python list dictionary

我有一个包含以下数据的列表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]}

有没有办法将所有数据从列表转换为字典而不会覆盖它?

1 个答案:

答案 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)