I have a list of dictionaries(over a thousand) from an API response that I reordered based on some other logic. Each list of dict’s has an ID. My goal is to update the ID to start at 0 again and increment 1 for each list. Here is an example of what I have:
JavaScript
x
13
13
1
list_of_dicts = [
2
{
3
'id': 5,
4
'age': 22,
5
'name': 'Bryan'
6
},
7
{
8
'id': 0,
9
'age': 28,
10
'name': 'Zach'
11
},
12
]
13
And what I need:
JavaScript
1
13
13
1
list_of_dicts = [
2
{
3
'id': 0,
4
'age': 22,
5
'name': 'Bryan'
6
},
7
{
8
'id': 1,
9
'age': 28,
10
'name': 'Zach'
11
},
12
]
13
Below is my current code. I keep getting an error of ‘int’ object has no attribute ‘update’ or a str error, probably because it’s iterating past id
.
Combined
holds my list of dictionaries.
JavaScript
1
9
1
counter = 0
2
for i in combined:
3
for k,v in i.items():
4
if k == 'id':
5
v.update({'id': counter})
6
counter += 1
7
else:
8
continue
9
Can someone guide me on where I’m going wrong at?
Advertisement
Answer
You don’t need a nested loop to update the id
element of the dictionary. Just index it directly.
JavaScript
1
3
1
for i, d in enumerate(list_of_dicts):
2
d['id'] = i
3