如何读取API输出的字典的多个列表?

时间:2019-04-23 16:12:06

标签: python-3.x list dictionary

我有一个应用程序,它以这种确切格式返回多个字典列表:

 [{'key1':'value1','key2':'value2'}][{'key3':'value3','key4':'value4'}]

我怎样才能按原样阅读整个词典列表,并将这些列表分开以在以后的代码中进行进一步分析?

我试图像这样将数据读入一个变量:

  a = [{'key1':'value1','key2':'value2'}][{'key3':'value3','key4':'value4'}]

但出现错误:

TypeError: list indices must be integers or slices, not dict

2 个答案:

答案 0 :(得分:2)

处理您制作的字符串的一种粗略方法是执行string.split,而string.replace如下。

import ast

a = "[{'key1':'value1','key2':'value2'}][{'key3':'value3','key4':'value4'}]"
li = []
#split of ']['
for elem in a.split(']['):
    #Replace elements in dictionary to make the string json compliant
    d = elem.strip('[]')
    #Use literal_eval to convert to dictionary
    dct = ast.literal_eval(d)
    #Append parsed dictionary to a list
    li.append(dct)

print(li)
#[{'key1': 'value1', 'key2': 'value2'}, {'key3': 'value3', 'key4': 'value4'}]

答案 1 :(得分:0)

您也可以这样尝试。使用以下建议的方法的好处是:

  • 无论字符串中有多少个字典,它都可以[{...}][{...}][{...}]使用。

  • 无论][之间有多少空格,它都可以[{...}] [{...}] [{...}] [{...}]使用。

感谢正则表达式。

因此,请看下面我尝试简化/解决您的问题的地方。

>>> import re
>>> import json
>>> 
>>> a = "[{'key1':'value1','key2':'value2'}][{'key3':'value3','key4':'value4'}]"
>>> 
>>> # Create a list of dictionaries from the exisitng string (valid for many dicts)
... # If there will be spaces b/w ] & [ or before/after [ & ], it will work
... 
>>> a = re.sub(r"\s*\]\s*\[\s*", ", ", a)
>>> a
"[{'key1':'value1','key2':'value2'}, {'key3':'value3','key4':'value4'}]"
>>> 
  

注意:JSON使用"包围键和值(字符串)。因此,如果我们尝试将其转换成字典列表,则用'转换上述字符串将引发Exception。

>>> a = json.loads(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 355, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
>>> 
  

让我们对其进行修复,首先将所有'替换为",然后再使用json.loads()从其字符串表示形式中获取实际对象。

>>> a = a.replace("'", '"')
>>> a
'[{"key1":"value1","key2":"value2"}, {"key3":"value3","key4":"value4"}]'
>>> 
>>> a = json.loads(a)
>>> a
[{'key1': 'value1', 'key2': 'value2'}, {'key3': 'value3', 'key4': 'value4'}]
>>> 
  

检查上面创建的列表。

>>> a[0]
{'key1': 'value1', 'key2': 'value2'}
>>> 
>>> a[1]
{'key3': 'value3', 'key4': 'value4'}
>>> 
>>> a[1]["key3"]
'value3'
>>>
>>> a[1]["key4"]
'value4'
>>>