Skip to content
Advertisement

How to skip items in a dictionary

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:

list_of_dicts = [
 {
  'id':   5,
  'age': 22,
  'name': 'Bryan'
 },
 {
  'id':   0,
  'age': 28,
  'name': 'Zach'
 },
]

And what I need:

list_of_dicts = [
 {
  'id':   0,
  'age': 22,
  'name': 'Bryan'
 },
 {
  'id':   1,
  'age': 28,
  'name': 'Zach'
 },
]

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.

    counter = 0
    for i in combined:
        for k,v in i.items():
            if k == 'id':
                v.update({'id': counter})
                counter += 1
            else:
                continue

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.

for i, d in enumerate(list_of_dicts):
    d['id'] = i
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement