0
0
Pythonprogramming~5 mins

Dictionary use cases in Python

Choose your learning style9 modes available
Introduction
Dictionaries help you store and find data quickly using keys, like a real-life address book.
When you want to look up a phone number by a person's name.
When you need to count how many times each word appears in a text.
When you want to group items by categories, like sorting fruits by color.
When you want to store settings or options with names and values.
When you want to update or change information easily without searching through a list.
Syntax
Python
my_dict = {key1: value1, key2: value2, ...}
Keys must be unique and usually are strings or numbers.
Values can be any type: numbers, strings, lists, or even other dictionaries.
Examples
A dictionary storing names as keys and phone numbers as values.
Python
phone_book = {'Alice': '123-456', 'Bob': '987-654'}
Counting how many times each word appears.
Python
word_count = {'hello': 3, 'world': 2}
Storing user settings with names and values.
Python
settings = {'volume': 10, 'brightness': 70, 'language': 'English'}
Sample Program
This program shows how to create a dictionary, access a value by key, add a new item, and loop through all items.
Python
fruits = {'apple': 'red', 'banana': 'yellow', 'grape': 'purple'}

# Print the color of banana
print(fruits['banana'])

# Add a new fruit
fruits['orange'] = 'orange'

# Print all fruits and their colors
for fruit, color in fruits.items():
    print(f"{fruit} is {color}")
OutputSuccess
Important Notes
Trying to access a key that does not exist will cause an error. Use .get() to avoid this.
Dictionaries do not keep order before Python 3.7, but now they remember the order items were added.
Keys must be immutable types like strings, numbers, or tuples.
Summary
Dictionaries store data as key-value pairs for fast lookup.
Use dictionaries when you want to find or update data by a name or label.
You can add, change, or loop through dictionary items easily.