Home > Back-end >  update values in a list of dictionnaries
update values in a list of dictionnaries

Time:07-21

I have the following list:

list_dict = [
        {'name': 'Old Ben', 'age': 71, 'country': 'Space', 'hobbies': ['getting wise']},
        {'name': 'Han', 'age': 26, 'country': 'Space', 'hobbies': ['shooting']},
        {'name': 'Luke', 'age': 24, 'country': 'Space', 'hobbies': ['being arrogant']},
        {'name': 'R2', 'age': 'unknown', 'country': 'Space', 'hobbies': []}
    ]

I would like to add a hobby to R2:

for i in range(len(list_dict)):
    people = list_dict[i]
    if people['name'] == 'R2':
        people['hobbies'] = ['lubrication']
print(list_dict)

I got what I was expecting but as a newbie I'd like to learn a few easy tricks to make it shorter.

CodePudding user response:

I'd express as:

people = {person['name']: person for person in list_dict}

people['R2']['hobbies']  = ['lubrication']  # reads nicely as "add a hobby to R2"

CodePudding user response:

You can just iterate over the list and condense the if statement:

for person in list_dict:
    person['hobbies'] = ['lubrication'] if person['name'] == 'R2' else person['hobbies']

CodePudding user response:

there is no need to loop over the lenght, you can loop through the list and you can condense with a one-liner if statement

for person in list_dict:
    person['hobbies'].append('lubrification') if person['name'] == 'R2' else ...

you can also do this with a generator:

[person['hobbies'].append('lubrification') for person in list_dict if person['name']]

But, if you just want to change one, you can use this code:

from operator import itemgetter
idx = map(itemgetter("name"),list_dict).index("R2")
list_dict[idx]["hobbies"].append("lubrification")
  • Related