簡體   English   中英

將列表列表轉換為字典字典

[英]Converting list of lists to dictionary of dictionaries

我有一個像下面這樣的字符串列表

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'> 我該如何解決這個問題?

我想這個也許你需要

  • 使用json.loads的元素轉換的string_list到字典
  • 通過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"},
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM