Python Dictionaries
Complete guide to Python dictionaries covering creation, access, modification, looping, and nesting.
Defining Dictionaries
# Making a dictionary
alien = {'color': 'green', 'points': 5}
Accessing Values
alien = {'color': 'green', 'points': 5}
# Get value with key
print(alien['color']) # green
print(alien['points']) # 5
# Using get() method (safe)
alien_points = alien.get('points', 0) # returns 0 if key not found
Adding Key-Value Pairs
alien = {'color': 'green', 'points': 5}
# Add new pairs
alien['x'] = 0
alien['y'] = 25
alien['speed'] = 1.5
Modifying Values
alien = {'color': 'green', 'points': 5}
print(alien)
# Change values
alien['color'] = 'yellow'
alien['points'] = 10
print(alien)
Looping Through
fav_langs = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby'
}
# Loop through all key-value pairs
for name, language in fav_langs.items():
print(f"{name}: {language}")
# Loop through all keys
for name in fav_langs.keys():
print(name)
# Loop through all values
for language in fav_langs.values():
print(language)