将列表列表转换为字典字典

时间:2021-07-13 01:28:26

标签: python json python-3.x dictionary

我有一个像下面这样的字符串列表

string_list = ['''{"no" : 1, "name": "John Doe", "address": "123, Einstein St, SA, 28372"}''', '''{'no" : 1, "name": "John Denver", "address": "454, BohrSt, SA, 64584"}''']

我正在尝试将列表中的每个字符串转换为字典并将其附加到字典中。

import json
newdict = {}
for string in string_list:
    new = json.loads(string)
    newdict.update(new)

但它产生了一个错误:

raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

但是如果我这样做了,

new = json.loads(string_list[1])

它有效。并给出 new 的类型为 <class 'dict'>。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我认为你可能需要这个

  • 使用json.loadsstring_list的元素转换为dict
  • 通过 dict comprehension 将列表列表转换为字典字典

代码:

import json
string_list = ['{"no" : 1, "name": "John Doe", "address": "123, Einstein St, SA, 28372"}', '{"no" : 1, "name": "John Doe", "address": "123, Einstein St, SA, 28372"}']
print({idx:json.loads(data) for idx,data in enumerate(string_list)})

结果:

{
    0: {"no": 1, "name": "John Doe", "address": "123, Einstein St, SA, 28372"},
    1: {"no": 1, "name": "John Doe", "address": "123, Einstein St, SA, 28372"},
}
相关问题