Python Forum

Full Version: How can I change value of dict in list?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have it
phone_books = [
    {'id': 0, 'name': 'Mike', 'number': 1111111},
    {'id': 1, 'name': 'Sasha', 'number': 2222},
]
I resolved it like that:
for x in phone_books:
    if x.get('id', 0) == 1:
        x['name'] = 'Vika'
        print(x)
Maybe there is better the way ?
It depends. Currently you could do phone_books[1]['name'] = 'Vika', since all of your id's match the list index. If that is not necessarily going to be true, and you are mainly going to be looking up by id, you might go with a dictionary keyed by id:

phone_books = {
    0: {'id': 0, 'name': 'Mike', 'number': 1111111},
    1: {'id': 1, 'name': 'Sasha', 'number': 2222},
}
Then phone_books[1]['name'] = 'Vika' still works. Again, having a dictionary instead of a list might not work with other parts of your code.