A dictionary in Python is an unordered collection of data stored in key-value pairs. Unlike lists and tuples, which store a sequence of elements, dictionaries store data as key-value pairs. Each key in a dictionary must be unique, and the values can be of any data type.
You can create a dictionary by placing key-value pairs inside curly braces, separated by a colon (:
), and each key-value pair is separated by a comma.
# Creating a Dictionary student = { "name": "John", "age": 25, "city": "New York" } print(student) # Output: {'name': 'John', 'age': 25, 'city': 'New York'}
You can access the values in a dictionary by referencing the key inside square brackets []
or using the get()
method.
# Accessing Values student = {"name": "John", "age": 25, "city": "New York"} print(student["name"]) # Output: John # Using get() method print(student.get("age")) # Output: 25
You can change the value of a key by directly assigning a new value to it, or by using the update()
method.
# Modifying Dictionary Values student = {"name": "John", "age": 25, "city": "New York"} student["age"] = 26 # Modifies the value of 'age' print(student) # Output: {'name': 'John', 'age': 26, 'city': 'New York'} # Using update() method student.update({"city": "Los Angeles"}) print(student) # Output: {'name': 'John', 'age': 26, 'city': 'Los Angeles'}
You can add new key-value pairs to a dictionary by assigning a value to a new key.
# Adding Items to a Dictionary student = {"name": "John", "age": 25, "city": "New York"} student["gender"] = "Male" # Adding a new key-value pair print(student) # Output: {'name': 'John', 'age': 25, 'city': 'New York', 'gender': 'Male'}
You can remove items from a dictionary using the del
statement or the pop()
method.
- del
: Deletes a specific key-value pair.
- pop()
: Removes and returns the value associated with a key.
# Removing Items from a Dictionary student = {"name": "John", "age": 25, "city": "New York", "gender": "Male"} # Using del statement del student["age"] print(student) # Output: {'name': 'John', 'city': 'New York', 'gender': 'Male'} # Using pop() method city = student.pop("city") print(city) # Output: New York print(student) # Output: {'name': 'John', 'gender': 'Male'}
You can retrieve the keys or values of a dictionary using the keys()
and values()
methods, respectively.
# Dictionary Keys and Values student = {"name": "John", "age": 25, "city": "New York"} # Getting Keys print(student.keys()) # Output: dict_keys(['name', 'age', 'city']) # Getting Values print(student.values()) # Output: dict_values(['John', 25, 'New York'])
You can find the number of key-value pairs in a dictionary using the len()
function.
# Dictionary Length student = {"name": "John", "age": 25, "city": "New York"} print(len(student)) # Output: 3
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!