Python Forum
How can I change value of dict in list?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can I change value of dict in list?
#1
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 ?
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Change font in a list or tuple apffal 4 3,922 Jun-16-2023, 02:55 AM
Last Post: schriftartenio
  How to change the datatype of list elements? mHosseinDS86 9 4,006 Aug-24-2022, 05:26 PM
Last Post: deanhystad
  Membership test for an element in a list that is a dict value for a particular key? Mark17 2 2,123 Jul-01-2022, 10:52 PM
Last Post: Pedroski55
  find some word in text list file and a bit change to them RolanRoll 3 2,538 Jun-27-2022, 01:36 AM
Last Post: RolanRoll
  Are list/dict comprehensions interpreted really sequentially? anata2047 3 2,421 May-31-2022, 08:43 PM
Last Post: Gribouillis
  Updating nested dict list keys tbaror 2 2,054 Feb-09-2022, 09:37 AM
Last Post: tbaror
  Change a list to integer so I can use IF statement buckssg 3 3,367 Sep-21-2021, 02:58 AM
Last Post: bowlofred
  change csv file into adjency list ainisyarifaah 0 1,963 Sep-21-2021, 02:49 AM
Last Post: ainisyarifaah
  How to change odd to even numbers in the list? plumberpy 8 5,871 Aug-08-2021, 11:07 AM
Last Post: plumberpy
  Question about change hex string to integer sting in the list (python 2.7) lzfneu 1 3,420 May-24-2021, 08:48 AM
Last Post: bowlofred

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020