Skip to main content

Introduction to Python Dictionaries

Python Dictionaries

A dictionary is an unordered collection of key-value pairs.

It is also known as an associative array or hash table. Dictionaries are defined by enclosing the key-value pairs in curly braces {} or by using the dict() constructor.

Each key in a dictionary must be unique, and it is used to access its corresponding value.

Here's an example of a dictionary in Python:

person = {
"name": "John",
"age": 30,
"city": "New York"
}

Accessing Dictionary Values

You can access the value associated with a key in a dictionary by using the key inside square brackets [].

person = {
"name": "John",
"age": 30,
"city": "New York"
}

print(person["name"]) # Output: John
print(person["age"]) # Output: 30

Adding and Modifying Dictionary Elements

You can add a new key-value pair to a dictionary by assigning a value to a new or existing key.

person = {
"name": "John",
"age": 30,
"city": "New York"
}

person["occupation"] = "Engineer" # Add a new key-value pair
person["age"] = 31 # Modify the value of an existing key

print(person) # Output: {'name': 'John', 'age': 31, 'city': 'New York', 'occupation': 'Engineer'}

Dictionary Methods

Dictionaries have several built-in methods that you can use, such as keys(), values(), items(), get(), pop(), popitem(), clear(), update(), and more.

person = {
"name": "John",
"age": 30,
"city": "New York"
}

print(person.keys()) # Output: dict_keys(['name', 'age', 'city'])
print(person.values()) # Output: dict_values(['John', 30, 'New York'])
print(person.items()) # Output: dict_items([('name', 'John'), ('age', 30), ('city', 'New York')])

print(person.get("name")) # Output: John
print(person.pop("age")) # Output: 30
print(person) # Output: {'name': 'John', 'city': 'New York'}

person.clear() # Remove all elements from the dictionary
print(person) # Output: {}

Checking Dictionary Membership

You can check if a key exists in a dictionary using the in operator. It returns True if the key is found in the dictionary and False otherwise.

person = {
"name": "John",
"age": 30,
"city": "New York"
}

print("name" in person) # Output: True
print("occupation" in person) # Output: False