ByteBoard Notes Notes

Update, delete and clear dictionary entries and display keys, values and items

Informatics Practices XI · Experiment 19 of 36 · Python

11-IPPython programs
Expt. No.19
Page No.38

Dictionary methods

Aim

To write a Python program that uses the dictionary functions and methods dict(), len(), keys(), values(), items(), update(), del and clear().

Concepts used

Algorithm

  1. Create a dictionary of book prices with dict().
  2. Display its length, keys, values and items.
  3. Merge new entries with update(); change a value; delete one entry with del.
  4. Empty the dictionary with clear().

Program

# Dictionary functions and methods books = dict(Python=450, SQL=380, Pandas=520)print("Dictionary:", books)print("Length    :", len(books))print("Keys      :", books.keys())print("Values    :", books.values())print("Items     :", books.items()) books.update({"NumPy": 300, "SQL": 400})print("After update():", books)del books["Pandas"]print("After del      :", books)books.clear()print("After clear()  :", books, "length", len(books))

A marked line continues the line above it. In your file, write it on the same line.

Output

$ python dictionary_methods.py
Dictionary: {'Python': 450, 'SQL': 380, 'Pandas': 520} Length : 3 Keys : dict_keys(['Python', 'SQL', 'Pandas']) Values : dict_values([450, 380, 520]) Items : dict_items([('Python', 450), ('SQL', 380), ('Pandas', 520)]) After update(): {'Python': 450, 'SQL': 400, 'Pandas': 520, 'NumPy': 300} After del : {'Python': 450, 'SQL': 400, 'NumPy': 300} After clear() : {} length 0

✓ Printed by running this program, not typed by hand.

Result

dict() built a dictionary of 3 books. update() added NumPy and changed the price of SQL to 400 in one step, del removed Pandas, and clear() left an empty dictionary of length 0.

Viva voce: what the examiner may ask

01What does update() do when a key already exists?

It replaces that key's value; new keys are added.

02What is the difference between del books and books.clear()?

del books removes the dictionary itself; clear() empties it but keeps it.

03Are dictionaries mutable?

Yes. Items can be added, changed and removed.

Variations for the lab test

  1. Add a book only if it is not already in the dictionary.
  2. Display the books costing more than 400.
  3. Delete every book that costs less than 400 (copy the keys into a list first).
! Common mistake Deleting a key that doesn't exist (del books["Java"]) raises KeyError.
Back to the 11-IP index