Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading