DE EN

Dictionaries & Sets

Key-value pairs and unique collections — the data structures for real projects.

50 Min Mittel

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")
Python
# 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)
Ausgabe
DragonSlayer99 12 {'name': 'DragonSlayer99', 'level': 13, 'hp': 100, 'xp': 450}
Python vs. JavaScript — Das kennst du schon!

Du kennst bereits JavaScript aus dem JS-Quest. Hier ist der direkte Vergleich:

Python
spieler = {"name": "Max", "level": 5}
print(spieler["name"])
print(spieler.get("level"))
JavaScript
let spieler = { name: "Max", level: 5 };
console.log(spieler.name);
console.log(spieler.level);
Merke: Python dicts are like JavaScript objects. Access in Python is 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.

Python
# 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
Ausgabe
['name', 'alter', 'ort'] ['Anna', 17, 'Wien'] name: Anna alter: 17 ort: Wien 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.

Python
# 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
Ausgabe
{'Tokio', 'New York', 'Paris'} {1, 2, 3, 4, 5, 6} {3, 4} {1, 2} True False
Python vs. JavaScript — Das kennst du schon!

Du kennst bereits JavaScript aus dem JS-Quest. Hier ist der direkte Vergleich:

Python
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b)
print(3 in a)
JavaScript
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));
Merke: Python has | 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.

Python
# 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}
Ausgabe
{'Anna': 4, 'Ben': 3, 'Clara': 5} {2: 4, 4: 16, 6: 36} {'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.

Python
# 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']}")
Ausgabe
Level-Up! Du bist jetzt Level 8! PyKnight — Level 8 XP: 3900 Rüstung: Lederpanzer

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"))

Solution
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")

Solution
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']}")

Solution
# 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']}")
Didactic Break

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