Python Dictionary


In this tutorial, we will explore the concept of dictionaries in Python.

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

It provides a way to store and retrieve data using unique keys.

Dictionaries are also known as associative arrays, hash maps, or hash tables in other programming languages.

We will cover various operations and methods available for working with dictionaries in Python.

 

Creating a Dictionary


To create a dictionary in Python, you can use curly braces ({}) and separate the key-value pairs with colons (:).

Here's an example:
 

# Empty dictionary
my_dict1 = {}

# Dictionary with key-value pairs
my_dict2 = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

# Using the dict() constructor
my_dict3 = dict(name="Bob", age=30, city="London")


In the above examples, ‘my_dict2’ and ‘my_dict3’ are dictionaries with the keys "name", "age", and "city", and their corresponding values.

 

Accessing Values in a Dictionary


Values in a dictionary can be accessed using their keys. To retrieve a value, you can use the square bracket notation dict[key]. If the specified key does not exist in the dictionary, a KeyError will be raised.

Here's an example:

my_dict = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

print(my_dict["name"])  # Output: Alice
print(my_dict["age"])  # Output: 25


Modifying Values in a Dictionary


You can modify the value associated with a key in a dictionary by assigning a new value to it. If the key does not exist, it will be added to the dictionary with the specified value.


Here's an example:

my_dict = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

my_dict["age"] = 26  # Modifying the value of the "age" key
my_dict["country"] = "USA"  # Adding a new key-value pair

print(my_dict)  # Output: {'name': 'Alice', 'age': 26, 'city': 'New York', 'country': 'USA'}


Dictionary Methods


Python provides many built-in methods for working with dictionaries. Here are some commonly used dictionary methods:

dict.keys(): Returns a view object that contains the keys of the dictionary.
dict.values(): Returns a view object that contains the values of the dictionary.
dict.items(): Returns a view object that contains the key-value pairs of the dictionary as tuples.
dict.get(key, default): Returns the value associated with the specified key. If the key does not exist, it returns the default value (default is None).
dict.pop(key): Removes the key-value pair with the specified key from the dictionary and returns the value.
dict.update(other_dict): Updates the dictionary with the key-value pairs from other_dict.
dict.clear(): Removes all key-value pairs from the dictionary.


Here's an example that demonstrates the usage of some of these methods:
 

my_dict = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

print(my_dict.keys())  # Output: dict_keys(['name', 'age', 'city'])
print(my_dict.values())  # Output: dict_values(['Alice', 25, 'New York'])
print(my_dict.items())  # Output: dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')])

print(my_dict.get("name"))  # Output: Alice
print(my_dict.get("country"))  # Output: None

print(my_dict.pop("age"))  # Output: 25
print(my_dict)  # Output: {'name': 'Alice', 'city': 'New York'}

other_dict = {"country": "USA", "occupation": "Engineer"}
my_dict.update(other_dict)
print(my_dict)  # Output: {'name': 'Alice', 'city': 'New York', 'country': 'USA', 'occupation': 'Engineer'}

my_dict.clear()
print(my_dict)  # Output: {}


These are just a few examples of the many dictionary methods available in Python. You can explore more dictionary methods in the Python documentation.

 

Dictionary Iteration


You can iterate over a dictionary's keys, values, or key-value pairs using loops.

Here are a few examples:

my_dict = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

# Iterating over keys
for key in my_dict:
    print(key)

# Iterating over values
for value in my_dict.values():
    print(value)

# Iterating over key-value pairs
for key, value in my_dict.items():
    print(key, value)

 

Summary 


In this tutorial, we covered the basics of working with dictionaries in Python. We learned how to create dictionaries, access values using keys, modify values, use dictionary methods, and iterate over dictionaries. Dictionaries are useful for storing and retrieving data based on unique identifiers (keys). With the knowledge gained from this tutorial, you should be able to effectively use dictionaries in your Python programs for various tasks.
 

© 2022-2023 All rights reserved.