What is a dictionary in Python example?

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;

    by
  • Dmytro Iliushko

    I am a middle python software engineer with a bachelor's degree in Software Engineering from Kharkiv National Aerospace University. My expertise lies in Python, Django, Flask, Docker, REST API, Odoo development, relational databases, and web development. I am passionate about creating efficient and scalable software solutions that drive innovation in the industry.

Leave a Comment