Dictionaries and its Methods

Introduction to Dictionaries

  • Unordered, Mutable collection of key-value pairs separated by comma , enclosed in {}
  • Keys must be unique and immutable (string, number, tuple) but values can be any data type
  • Used to store and lookup data using keys instead of index
  • Examples:
    1. my_dict = {"name": "Rabindra", "age": 30, "city": "Kathmandu"} print(my_dict) # {'name': 'Rabindra', 'age': 30, 'city': 'Kathmandu'} my_dict = {1: "one", (2, 3): "tuple key", "list": [1, 2, 3]} print(my_dict) # {1: 'one', (2, 3): 'tuple key', 'list': [1, 2, 3]}

Dictionary Methods

  • Functions that perform operations on dictionaries and return a new dictionary or modify the existing
  • Data Related Operations: get(), keys(), values(), items(), update(), pop()
  • Other: Membership, len(), copy()

Accessing Data

  • [] is used to access value in a dictionary. Key is used instead of index to access value.
  • .get() method is also used to access value. It doesn't give error if key is not found
  • Apart from access [] is also used to add/update key-value pairs in dictionary
  • Examples:
    1. course_info = {"name": "Python Basics", "duration": 40, "instructor": "Rabindra"} print(course_info["name"]) # Python Basics print(course_info.get("duration")) # 40 print(course_info.get("level")) # None (key not found) print(course_info.get("level", 0))course_info["level"] = "Beginner" print(course_info) # New key is added course_info["duration"] = 45 print(course_info) # Existing value is updated

Keys, Values and Items

  • .keys() returns a view of all keys in the dictionary
  • .values() returns a view of all values in the dictionary
  • .items() returns a view of all key-value pairs in the dictionary
  • Examples:
    1. my_dict = {"name": "Rabindra", "age": 30, "city": "Kathmandu"} print(my_dict.keys()) # dict_keys(['name', 'age', 'city']) print(my_dict.values()) # dict_values(['Rabindra', 30, 'Kathmandu']) print(my_dict.items()) # dict_items([('name', 'Rabindra'), ('age', 30), ('city', 'Kathmandu')])
    2. student_info = {"name": "Bob", "age": 25, "grade": "A"} print(student_info.keys()) # dict_keys(['name', 'age', 'grade']) print(student_info.values()) # dict_values(['Bob', 25, 'A']) print(student_info.items()) # dict_items([('name', 'Bob'), ('age', 25), ('grade', 'A')])

update

  • Used to update a dictionary with key-value pairs from another dictionary
  • If a key already exists, its value will be updated else new record will be added to the original dictionary.
  • Examples:
    1. my_dict = {"name": "Rabindra", "age": 30} update_dict = {"age": 35, "city": "Kathmandu"} my_dict.update(update_dict) print(my_dict) # {'name': 'Rabindra', 'age': 35, 'city': 'Kathmandu'}
    2. student_info = {"name": "Bob", "age": 25, "grade": "A"} update_info = {"grade": "A+", "city": "Los Angeles"} student_info.update(update_info) print(student_info) # {'name': 'Bob', 'age': 25, 'grade': 'A+', 'city': 'Los Angeles'}

pop

  • Used to remove a key from the dictionary and return its value
  • Examples:
    1. my_dict = {"name": "Rabindra", "age": 30, "city": "Kathmandu"} removed_value = my_dict.pop("age") print(removed_value) # 30 print(my_dict) # {'name': 'Rabindra', 'city': 'Kathmandu'} student_info = {"name": "Bob", "age": 25, "grade": "A"} removed_grade = student_info.pop("grade") print(removed_grade) # A print(student_info) # {'name': 'Bob', 'age': 25}

len

  • Used to find the number of key-value pairs in a dictionary
  • Examples:
    1. my_dict = {"name": "Rabindra", "age": 30, "city": "Kathmandu"} print(len(my_dict)) # 3 student_info = {"name": "Bob", "age": 25, "grade": "A"} print(len(student_info)) # 3

copy

  • Used to create a copy of a dictionary to avoid modifying the original dictionary
  • Examples:
    1. original_dict = {"name": "Rabindra", "age": 30} copied_dict = original_dict copied_dict["age"] = 35 print(original_dict) # {'name': 'Rabindra', 'age': 35} print(copied_dict) # {'name': 'Rabindra', 'age': 35} another_copy = original_dict.copy() another_copy["age"] = 40 print(original_dict) # {'name': 'Rabindra', 'age': 35} print(another_copy) # {'name': 'Rabindra', 'age': 40}

Membership

  • Used to check if a key is present in the dictionary
  • Examples:
    1. my_dict = {"name": "Rabindra", "age": 30, "city": "Kathmandu"} print("name" in my_dict) # True print("country" in my_dict) # False student_info = {"name": "Bob", "age": 25, "grade": "A"} print("grade" in student_info) # True print("email" in student_info) # False
  • NOTE - Membership operator in checks for presence of key in the dictionary, not value.
  • For value, we use in operator with .values(). i.e. 'Kathmandu' in my_dict.values()

range

  • Used to generate a sequence of numbers within a specified range
  • Has three parameters: start (inclusive), stop (exclusive) and step (optional, default is 1)
  • Syntax: range(start, stop, step)
  • Examples:
    1. print(list(range(5))) # [0, 1, 2, 3, 4] print(list(range(1, 6))) # [1, 2, 3, 4, 5] print(list(range(0, 10, 2))) # [0, 2, 4, 6, 8] print(list(range(10, 0, -1))) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Collection Data Comparison

Comparison of Collection Data Types
PropertyListTupleSetDictionary
OrderedYesYesNoNo (Yes in recent versions)
MutableYesNoYesYes
UniqueNoNoYesYes (key)
Comparison of collection data types