Home > Back-end >  How to alter the name of a key in each dictionary in a list of dictionaries
How to alter the name of a key in each dictionary in a list of dictionaries

Time:03-25

Let's say I have the following list of dictionaries, my_list:

[
{'nsme':'bob',
 'age':37,
},
{'nsme':'amy',
 'age':40,
},
{'nsme':'pat',
 'age':28,
}
]

How can I create a new list that corrects the spelling of 'name'? I figured out how to do it for any single dict in my_list:

{'name' if k == 'nsme' else k:v for k,v in my_list[0].items()}

But when I try to loop through the items in my_list:

[{'name' if k == 'nsme' else k:v for k,v in my_list[i].items()} for i in my_list]

or

{'name' if k == 'nsme' else k:v for k,v in my_list[i].items() for i in my_list}

I get an error:

TypeError: list indices must be integers or slices, not dict

For context, I ran a pretty lengthy process to scrape a lot of data but accidentally had a typo in naming the 'name' key. Rather than fixing this and rescraping everything again, I figured it'd be a lot easier to just create a new list that fixes the typo.

CodePudding user response:

i refers to a dictionary in the list, not an index. So, your dictionary comprehension should be:

[{'name' if k == 'nsme' else k:v for k,v in elem.items()} for elem in my_list]

(I've renamed i renamed to elem in this code snippet for clarity.)

CodePudding user response:

I think what you are looking for is:

[{'name' if key == 'nsme' else key: value for key, value in d.items()} for d in my_list]

When looping over a list of dictionaries the elements you get returned are dictionaries, not indices of a list. Hence the error that the list indices need to be integers or slices, not a dicationary.

  • Related