Python Dictionary


A Python dictionary is a collection of key-value pairs. It is one of Python's built-in data types, and it is highly useful for storing and organizing data.

Dictionary Properties

  • Unordered: Dictionaries do not maintain the order of items. However, starting from Python 3.7, dictionaries maintain the insertion order as an implementation detail i.e they are ordered now. In Python 3.8 and later, this behavior is officially guaranteed.
  • Mutable: Dictionaries are mutable, meaning that you can change, add, or remove items after the dictionary has been created.
  • Indexed by keys: Each item in a dictionary is accessed via a unique key. Keys must be immutable types, like strings, numbers, or tuples with immutable elements, while the values can be of any type.
  • Unique keys: Keys within a dictionary must be unique. If you use the same key multiple times, the last assignment will overwrite the previous one.

Example to show these properties:

Creating Dict -

# Creating a dictionary
student = {
    "name": "John Doe",
    "age": 20,
    "courses": ["Math", "Science"],
    "graduated": False
}

print(student)


Accessing elements in dict

# Creating a dictionary
student = {
    "name": "John Doe",
    "age": 20,
    "courses": ["Math", "Science"],
    "graduated": False
}

# Accessing values
print(student["name"])  # Output: John Doe
print(student["courses"])  # Output: ['Math', 'Science']


Adding New element to dict

# Creating a dictionary
student = {
    "name": "John Doe",
    "age": 20,
    "courses": ["Math", "Science"],
    "graduated": False
}

# Adding a new key-value pair
student["GPA"] = 3.8

print(student)


Modify existing key in dict

# Creating a dictionary
student = {
    "name": "John Doe",
    "age": 20,
    "courses": ["Math", "Science"],
    "graduated": False
}

# Modifying an existing key-value pair
student["age"] = 21

print(student)


Check if key exists in dict

# Creating a dictionary
student = {
    "name": "John Doe",
    "age": 20,
    "courses": ["Math", "Science"],
    "graduated": False
}

# Checking if a key exists
print("name" in student)  # Output: True
print("graduated" in student)  # Output: False


Iterating over in dict

# Creating a dictionary
student = {
    "name": "John Doe",
    "age": 20,
    "courses": ["Math", "Science"],
    "graduated": False
}

# Iterating over keys and values
for key, value in student.items():
    print(f"{key}: {value}")

# Output:
# name: John Doe
# age: 21
# courses: ['Math', 'Science']
# GPA: 3.8

Here -

  • The dictionary student contains keys such as "name", "age", "courses", and "graduated" with their respective values.
  • We access the values using their keys (e.g., student["name"]).
  • We add a new key-value pair with student["GPA"] = 3.8.
  • We modify an existing value with student["age"] = 21.
  • We remove a key-value pair using del student["graduated"].
  • We check for the existence of keys using the in keyword.
  • We iterate over the dictionary using a for loop to print all keys and their corresponding values.