将一串词典转换为词典列表

时间:2020-11-07 10:54:32

标签: python list dictionary

我有一个字符串,其中包含许多字典(1到n),我想将其更改为字典列表,如果它有多个字典,则可以正常工作:

str_dic = '{"Name": "banana", "Color": "yellow", "Count": "three"}, {"Name": "apple", "Color": "red", "Count": "five"}'
lst = list(eval(str_dic))
print(type(lst))
print(lst)

>>> <class 'list'>
>>> [{'Name': 'banana', 'Color': 'yellow', 'Count': 'three'}, {'Name': 'apple', 'Color': 'red', 'Count': 'five'}]

但是当字符串仅包含一个字典时,它仅返回键,而不返回值。

str_dic = '{"Name": "banana", "Color": "yellow", "Count": "three"}'
lst = list(eval(str_dic))
print(type(lst))
print(lst)

>>> <class 'list'>
>>> ['Name', 'Color', 'Count']

2 个答案:

答案 0 :(得分:1)

在eval之前在字符串上加上方括号可以解决此问题:

str_dic = '[{"Name": "banana", "Color": "yellow", "Count": "three"}, {"Name": "apple", "Color": "red", "Count": "five"}]'
lst = eval(str_dic)
print(lst)

str_dic = '[{"Name": "banana", "Color": "yellow", "Count": "three"}]'
lst = eval(str_dic)
print(lst)

输出:

[{'Name': 'banana', 'Color': 'yellow', 'Count': 'three'}]
[{'Name': 'banana', 'Color': 'yellow', 'Count': 'three'}, {'Name': 'apple', 'Color': 'red', 'Count': 'five'}]

答案 1 :(得分:1)

由于您正在使用JSON数据,因此需要使用Python的内置模块json。快速阅读注释将解释代码。

import json

str_dic = '...'
str_dic_list = str_dic.split('}, ')   # Split string dictionaries into list (see Note)
dic_list = []                         # Initialize an empty list for storing dictionaries

for dic in str_dic_list:              # Iterate through the list of string dictionaries
    temp_dic = dic.rstrip('}') + '}'  # Adds trailing "}" at the end of string dictionary (see Note)
    d = json.loads(temp_dic)          # Convert string dictionary (JSON) into dictionary
    dic_list.append(d)                # Append the converted dictionary in the list

注意:

在这里,我们使用str_dic.split('}, '),因为使用str_dic.split(', ')会拆分字典中的每个条目,而不是拆分字典本身。例如,它可能导致{'Name': 'banana'而不是{'Name': 'banana', 'Color': 'yellow', 'Count': 'three'}。好吧,不完全是。我们在每个结果的末尾都会丢失},因此我们得到类似{'Name': 'banana', 'Color': 'yellow', 'Count': 'three'的信息(请注意缺少的})。因此,为了弥补这一点,我们将在末尾连接大括号:dic + '}'。但这可能会导致最后一个字符串字典出现问题,因为它将保留花括号,因为此时不会发生拆分。因此,我们确保剥去大括号的末端,然后将其连接起来,即dic.rstrip('}') + '}'

输出


[{'Name': 'banana', 'Color': 'yellow', 'Count': 'three'}, {'Name': 'apple', 'Color': 'red', 'Count': 'five'}]
相关问题