Home > Net >  Change Values in a Dictionary
Change Values in a Dictionary

Time:12-06

I want to change values in a dictionary. for example I want to change the value 'Available' to 'Not Available'

    book_library_dict = {
    1: [1, 'Harry Potter and the Deathly Hallows', 'Bloomsbury', 'J K Rowling', 'Available', None, }

CodePudding user response:

Use the following syntax to refer to value stored in the key 1:

book_library_dict[1]

In this case, the value stored in the key 1 is a list, so you can do the following to replace the element Available with Not Available.

book_library_dict[1][book_library_dict[1].index('Available)] = 'Not Available'

This is not very pretty, so you might want to consider changing your variable structure to be a list of dictionaries. Something like:

book_library_dict = {
1: {'Number': 1, Title: 'Harry Potter and the Deathly Hallows', 
   ... 'Avilabaility': 'Available', ... }

You could then change the value with

book_library_dict[1]['Availability'] = 'Not Available'
  • Related