Lernziele dieses Kapitels
- You create dictionaries and safely access values
- You use get(), keys(), values() and items() professionally
- You use sets for unique values and set operations
- You build PyBuddy's user profile as a dictionary
Dictionary Basics
A dictionary is like a phone book or an inventory in a game: every value has a unique name (key). Instead of numeric indexes, you access values by name.
- Create:
spieler = {"name": "Max", "level": 5} - Access:
spieler["name"] - Safe access:
spieler.get("name")
# Dictionary erstellen
spieler = {
"name": "DragonSlayer99",
"level": 12,
"klasse": "Magier",
"hp": 100
}
print(spieler["name"]) # DragonSlayer99
print(spieler.get("level")) # 12
# Wert ändern
spieler["level"] = 13
spieler["xp"] = 450 # Neuer Schlüssel!
# Löschen
del spieler["klasse"]
print(spieler)
Du kennst bereits JavaScript aus dem JS-Quest. Hier ist der direkte Vergleich:
spieler = {"name": "Max", "level": 5}
print(spieler["name"])
print(spieler.get("level"))
let spieler = { name: "Max", level: 5 };
console.log(spieler.name);
console.log(spieler.level);
spieler["name"] or .get(), in JS spieler.name or ["name"].Methods and Nested Dicts
Dictionaries have powerful methods: keys(), values(), items(). And you can nest dictionaries inside each other — perfect for complex data structures like player profiles.
# Dictionary-Methoden
nutzer = {"name": "Anna", "alter": 17, "ort": "Wien"}
print(list(nutzer.keys())) # ['name', 'alter', 'ort']
print(list(nutzer.values())) # ['Anna', 17, 'Wien']
# items() liefert Schlüssel-Wert-Paare
for key, value in nutzer.items():
print(f"{key}: {value}")
# Verschachtelte Dicts
profil = {
"user": {"name": "Max", "id": 42},
"stats": {"level": 5, "xp": 1200},
"badges": ["Newbie", "Coder"]
}
print(profil["stats"]["level"]) # 5
Sets for Unique Values
A set is like a list, but each value occurs only once — duplicates are automatically removed. Sets are perfect for unique collections and set operations.
# Sets erstellen
besucht = {"Paris", "Tokio", "New York", "Paris"}
print(besucht) # {'Tokio', 'New York', 'Paris'} — keine Duplikate!
# Mengenoperationen
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # Vereinigung: {1, 2, 3, 4, 5, 6}
print(a & b) # Schnittmenge: {3, 4}
print(a - b) # Differenz: {1, 2}
# Prüfung
print(3 in a) # True
print(7 in a) # False
Du kennst bereits JavaScript aus dem JS-Quest. Hier ist der direkte Vergleich:
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b)
print(3 in a)
let a = new Set([1, 2, 3]);
let b = new Set([3, 4, 5]);
let vereinigung = new Set([...a, ...b]);
console.log(vereinigung);
console.log(a.has(3));
| and & directly as operators for sets. JavaScript uses Set objects and the spread operator ....Dict Comprehensions
Just like lists, dictionaries also have comprehensions. You create a dictionary in one line — elegant and pythonic.
# Dict Comprehension
namen = ["Anna", "Ben", "Clara"]
laengen = {name: len(name) for name in namen}
print(laengen) # {'Anna': 4, 'Ben': 3, 'Clara': 5}
# Mit Bedingung
zahlen = [1, 2, 3, 4, 5, 6]
quadrate = {z: z**2 for z in zahlen if z % 2 == 0}
print(quadrate) # {2: 4, 4: 16, 6: 36}
# Aus zwei Listen
keys = ["a", "b", "c"]
values = [1, 2, 3]
paar = {k: v for k, v in zip(keys, values)}
print(paar) # {'a': 1, 'b': 2, 'c': 3}
Dictionaries in Action: Player Profile
Imagine a complete player profile: name, level, XP, badges and equipment — all in a nested dictionary. This is the data structure that real games use internally.
# Spieler-Profil
spieler = {
"name": "PyKnight",
"level": 7,
"xp": 3400,
"badges": ["First Blood", "Level 5"],
"ausruestung": {
"waffe": "Stahlschwert",
"ruestung": "Lederpanzer",
"gold": 150
}
}
# XP hinzufügen
gewonnen = 500
spieler["xp"] += gewonnen
# Level-Up prüfen
if spieler["xp"] >= 4000:
spieler["level"] += 1
spieler["badges"].append(f"Level {spieler['level']}")
print(f" Level-Up! Du bist jetzt Level {spieler['level']}!")
# Profil anzeigen
print(f"\n {spieler['name']} — Level {spieler['level']}")
print(f" XP: {spieler['xp']}")
print(f" Rüstung: {spieler['ausruestung']['ruestung']}")
Warm-Up: Contact Book
Create a dictionary with 3 contacts (name → phone number). Use input() for a search and print the number or "Not found".
Hinweis: kontakte = {"Anna": "0664/123", "Ben": "0664/456", "Clara": "0664/789"}
name = input("Suche: ")
print(kontakte.get(name, " Nicht gefunden"))
kontakte = {"Anna": "0664/123", "Ben": "0664/456", "Clara": "0664/789"}
name = input("Suche: ")
print(kontakte.get(name, " Nicht gefunden"))
Challenge: Word Frequency
The user enters a sentence. Count how often each word occurs. Use a dictionary with words as keys and frequencies as values.
Hinweis: satz = input("Satz: ").lower()
woerter = satz.split()
haeufigkeit = {}
for wort in woerter:
haeufigkeit[wort] = haeufigkeit.get(wort, 0) + 1
for wort, anzahl in haeufigkeit.items():
print(f"{wort}: {anzahl}x")
satz = input("Satz: ").lower()
woerter = satz.split()
haeufigkeit = {}
for wort in woerter:
haeufigkeit[wort] = haeufigkeit.get(wort, 0) + 1
for wort, anzahl in haeufigkeit.items():
print(f"{wort}: {anzahl}x")
PyBuddy Checkpoint: User Profile
PyBuddy stores name, level, XP and badges in a dictionary. Display the profile formatted and allow adding XP.
Hinweis: # pybuddy/main.py
profil = {
"name": "Max",
"level": 1,
"xp": 0,
"badges": ["PyBuddy Nutzer"]
}
print(f" Profil von {profil['name']}")
print(f" Level {profil['level']} | {profil['xp']} XP")
print(f"🎖️ Badges: {', '.join(profil['badges'])}")
# XP hinzufügen
bonus = int(input("Bonus-XP: "))
profil["xp"] += bonus
print(f"Neuer XP-Stand: {profil['xp']}")
# pybuddy/main.py
profil = {
"name": "Max",
"level": 1,
"xp": 0,
"badges": ["PyBuddy Nutzer"]
}
print(f" Profil von {profil['name']}")
print(f" Level {profil['level']} | {profil['xp']} XP")
print(f"🎖️ Badges: {', '.join(profil['badges'])}")
# XP hinzufügen
bonus = int(input("Bonus-XP: "))
profil["xp"] += bonus
print(f"Neuer XP-Stand: {profil['xp']}")
In Pokémon, every monster is stored as a dictionary: name, type, HP, attack, defense, move list. When you catch a Pokémon, the game simply adds a new dict to your list. You are building the foundations for your own monster collection!
Zusammenfassung
- Dictionary = {'key': 'value'} — like a phone book
- get(), keys(), values(), items() for access
- Sets = {1, 2, 3} — only unique values
- Dict comprehensions for elegant creation
- Nested dicts for complex data