Course Content
How to Add a Virtual Environment in Python
0/1
Set
0/1
Python
About Lesson

In Python, a dictionary is an unordered collection of key-value pairs. Each key is unique within a dictionary, and each key is associated with a value. Dictionaries are widely used in Python because they provide an efficient way to store and retrieve data by keys.

1. Dictionary Basics

  • A dictionary in Python is created using curly braces {} or the dict() function.
  • Each element in a dictionary is a key-value pair. The key is immutable (usually strings, numbers, or tuples), while the value can be of any data type.

2. Creating a Dictionary

Using Curly Braces:

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

Using dict() Constructor:

Python
my_dict = dict(name="Alice", age=25, city="New York")

3. Accessing Dictionary Values

You can access the values in a dictionary by using the key in square brackets [], or by using the get() method.

Using Square Brackets:

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

Using get() Method:

Python
print(my_dict.get("age"))  # Output: 25

4. Adding and Modifying Dictionary Elements

You can add new key-value pairs or modify existing ones by assigning a value to a key.

Adding or Modifying:

Python
# Adding a new key-value pair
my_dict["email"] = "alice@example.com"

# Modifying an existing value
my_dict["age"] = 26

6. Dictionary Methods

Here are some commonly used methods with dictionaries:

  • keys(): Returns a view object containing all the keys.
  • values(): Returns a view object containing all the values.
  • items(): Returns a view object containing all the key-value pairs (tuples).
  • update(): Updates the dictionary with another dictionary or key-value pairs.
  • copy(): Returns a shallow copy of the dictionary.
  • get(): Returns the value for the specified key, or None if the key does not exist.

Example:

Python
my_dict = {"name": "Alice", "age": 25}

# keys() method
keys = my_dict.keys()  # dict_keys(['name', 'age'])

# values() method
values = my_dict.values()  # dict_values(['Alice', 25])

# items() method
items = my_dict.items()  # dict_items([('name', 'Alice'), ('age', 25)])

# update() method
my_dict.update({"email": "alice@example.com"})
print(my_dict)  # Output: {'name': 'Alice', 'age': 25, 'email': 'alice@example.com'}

# copy() method
new_dict = my_dict.copy()
print(new_dict)  # Output: {'name': 'Alice', 'age': 25, 'email': 'alice@example.com'}