简体   繁体   English

Python从具有key:value字符串的列表中创建字典

[英]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.

相关问题 如何从python中具有相同键和值的字符串列表创建字典 - How to create a dictionary from a list of strings with same key, value in python 创建一个 Python 字典,其中每个键都有一个列表作为值 - create a Python dictionary where for each key has a list as the value 创建一个 python 字典,其中值是字符串列表 - create a python dictionary where the value is a list of strings 如何在 Python 中的字典列表中使用另一个键列表中的值在字典中创建一个新键? - How to create a new key in dictionary with value from another key list from a list of dictionary in Python? Python-如果字符串列表不在字典键中,则从字典列表中删除字典 - Python - Remove dictionary from list of dictionaries if list of strings not in dictionary key Python:使用[0] =键和[1:] =值从列表创建字典 - Python: Create Dictionary From List with [0] = Key and [1:]= Values Python - 按字母(值)排序字典{String Key:字符串列表}? - Python - Sorting a dictionary {String Key: List of Strings} by len(value)? python 从值列表中获取字典键 - python get dictionary key from value is list 如何创建从具有多个键的 Python 字典中输出特定键值的 Python 程序? - How to Create a Python Program that Outputs a Specific Key Value from a Python Dictionary that has Multiple Keys? Python:字典的值是字符串列表 - Python: Value of dictionary is list of strings
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM