In Python, a dictionary is a native data structure designed to store a collection of key-value pairs. This data structure is commonly referred to as an associative array or hash map in other programming languages.
Each key-value pair in a dictionary is unique, and the keys are used to access their corresponding values efficiently.
How to create a dictionary with Python?
Here’s an example of how to create and use a dictionary in Python:
# Creating a dictionary
student = {
'name': 'John',
'age': 20,
'major': 'Computer Science',
'gpa': 3.5
}
# Accessing values using keys
print(student['name']) # Output: John
print(student['age']) # Output: 20
print(student['major']) # Output: Computer Science
print(student['gpa']) # Output: 3.5
# Modifying values
student['age'] = 21
student['gpa'] = 3.8
# Adding a new key-value pair
student['university'] = 'XYZ University'
# Removing a key-value pair
del student['major']
# Iterating over keys
for key in student.keys():
print(key)
# Iterating over values
for value in student.values():
print(value)
# Iterating over key-value pairs
for key, value in student.items():
print(key, value)
Code language: Python (python)
Output:
name
age
gpa
university
John
21
3.8
XYZ University
name John
age 21
gpa 3.8
university XYZ University
Code language: Python (python)
In the example above, we create a dictionary called student
with various key-value pairs representing different attributes of a student. We access values using the keys, modify values, add new key-value pairs, and remove existing key-value pairs. We can also iterate over the keys, values, or key-value pairs using the keys()
, values()
, and items()
methods, respectively.
Read More;
- What is TQDM in for loop Python?
- What is an example of a syntax error in Python?
- What is the dash function in Python?
- How to test a class with unittest Python?
- What is an example of a runtime error?
- How to run Python script from GitLab?
- What is an example of a string in Python?
- What is RegEx in Python with example?
- What is an example of a Boolean in Python?
- What is an example of built-in and user-defined functions in Python?
- What is an example of a constructor in Python?
- Python Example For Arithmetic Operations On Lists