[英]Python create dictionary from a list that has key:value strings
I have a list second_list
that contains the following data: 我有一个包含以下数据的列表
second_list
:
{"forename":"SomeForename","surname":"SomeSurname","title":"MR"}
{"postTown":"LONDON"}
{"country":"ZIMBABWE"}
{"forename":"SomeOtherForename","surname":"SomeOtherSurname"}
{"postTown":"LONDON"}
{"country":"ZIMBABWE"}
and I am trying to convert that list to a dictionary like this: 我正在尝试将该列表转换为像这样的字典:
dict_values = {}
for i in second_list:
dict_values.update(ast.literal_eval(i))
but the key and value of the dictionary get overwritten with the last key and value. 但是字典的键和值会被最后一个键和值所覆盖。 So, I get a dictionary with the following data:
因此,我得到了一个包含以下数据的字典:
{"forename":"SomeOtherForename","surname":"SomeOtherSurname"}
{"postTown":"LONDON"}
{"country":"ZIMBABWE"}
What I would like to achieve is to have dictionary with list as a value like this: 我想要实现的是将具有list的字典作为一个值,如下所示:
{'forename':[someForename, SomeOtherForename], 'surname:'[someSurname, someOtherSurname]}
etc. 等等
Is there a way to convert all the data from list to a dictionary without overwriting it? 有没有一种方法可以将列表中的所有数据转换为字典而不覆盖它?
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.