json 除了最后一个之外,不能在Python中将列表元素添加到dict中

siotufzp  于 2023-08-08  发布在  Python
关注(0)|答案(1)|浏览(117)

我有一个字典列表,我想把它们转换成一个字典,但问题是当我使用循环添加它们时,只有最后一个被添加注意,Reaquest返回一个我想转换成Python DIC的JSON对象列表。

import json

 import requests
 my_requset = requests.get("https://jsonplaceholder.typicode.com/users")

request_parse = my_requset.json()

new_dcit = {}

for i in request_parse:
    new_dcit.update(i)

for key , val in new_dcit.items():
     print(key ," : ", val)

字符串
如果有任何其他方法可以将JSON对象转换为DIC,请分享它

np8igboo

np8igboo1#

new_dict.update(i)只是替换当前数据。
如果你想保留它们,把它们保存在字典列表中,所以my_requset.json()。或者,在查看request_parse中的每个数据时分配一个唯一的键。
举例来说:

request_parse = my_requset.json()

new_dcit = {}

for i in request_parse:
    new_dict[i[id]] = i # I used id as the unique key

print(new_dict[2])

字符串
测试结果

{
    "id": 2,
    "name": "Ervin Howell",
    "username": "Antonette"
    ...
}

相关问题