我有一個來自 API 回應的字典串列(超過一千個),我根據其他一些邏輯重新排序。每個 dict 串列都有一個 ID。我的目標是更新 ID 以再次從 0 開始并為每個串列增加 1。這是我所擁有的一個例子:
list_of_dicts = [
{
'id': 5,
'age': 22,
'name': 'Bryan'
},
{
'id': 0,
'age': 28,
'name': 'Zach'
},
]
而我需要的是:
list_of_dicts = [
{
'id': 0,
'age': 22,
'name': 'Bryan'
},
{
'id': 1,
'age': 28,
'name': 'Zach'
},
]
下面是我目前的代碼。我不斷收到'int' object has no attribute 'update'或 str 錯誤的錯誤,可能是因為它正在迭代過去id。
Combined 保存著我的字典串列。
counter = 0
for i in combined:
for k,v in i.items():
if k == 'id':
v.update({'id': counter})
counter = 1
else:
continue
有人可以指導我哪里出錯了嗎?
uj5u.com熱心網友回復:
您不需要嵌套回圈來更新id字典的元素。直接索引就可以了。
for i, d in enumerate(list_of_dicts):
d['id'] = i
uj5u.com熱心網友回復:
如果您有一個 dict 串列,那么您可以遍歷串列列舉并更改 id:
for i,di in enumerate(list_of_dicts):
di['id'] = i
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/349385.html
標籤:Python
