Hello everyone, I am Xingyuan, a 19-year-old self-taught Python beginner 🤓. Today, we will unlock the magic of dictionaries! Using key-value pairs to store data, modeling the real world, and let’s tackle the Tic-Tac-Toe project together! 🚀
📌 Today’s Learning Content
👉 “Using dictionaries to store structured data, learning to query, modify, and delete, and modeling a Tic-Tac-Toe board!”
✨ Knowledge Points Explanation
1️⃣ Dictionary Data Type
-
Concept: A dictionary is a collection of key-value pairs, represented by
<span>{ }</span>. Keys must be unique. -
Example:
>>> myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'} >>> myCat['size'] 'fat' -
Empty Dictionary:
<span>{}</span>→ No key-value pairs.
2️⃣ Dictionaries vs Lists
-
Difference:
-
List: Values are stored by integer index, ordered.
-
Dictionary: Values are stored by keys, unordered, keys can be of any type (e.g., strings, numbers).
-
Example:
>>> spam = {'name': 'Zophie', 'age': 7} >>> spam['color'] # KeyError!
3️⃣ <span>keys()</span>, <span>values()</span>, <span>items()</span> Methods
-
Methods:
-
<span>keys()</span>→ Returns all keys -
<span>values()</span>→ Returns all values -
<span>items()</span>→ Returns all key-value pairs (in tuple form). -
Example:
>>> s = {'color': 'black', 'age': 12} >>> for i in s.keys(): ... print(i) ... color age
4️⃣ Checking Key Existence
-
Syntax:
>>> 'color' in s.keys() True >>> 'color' in s # Short form True
5️⃣ <span>get()</span> Method
-
Function: Safely retrieve a value, returns a default value if the key does not exist.
-
Syntax:
>>> picnicItems = {'apples': 5, 'cups': 2} >>> print(picnicItems.get('cups', 0)) 2 >>> print(picnicItems.get('eggs', 0)) 0
6️⃣ <span>setdefault()</span> Method
-
Function: Sets a default value if the key does not exist.
-
Syntax:
>>> s.setdefault('color', 'black') 'black' >>> s {'name': 'Xingyuan', 'age': 19, 'color': 'black'}
7️⃣ Pretty Print
-
Module:
<span>pprint</span>→ Formats and prints complex data structures. -
Example:
import pprint message = "Python is really amazing" count = {} for character in message: if character not in count: count[character] = 0 count[character] += 1 print("Character count:") pprint.pprint(count)
8️⃣ Tic-Tac-Toe Project
-
Goal: Model a Tic-Tac-Toe board using a dictionary and print its state.
-
Code:
game_state = { 'top-left': ' ', 'top-middle': ' ', 'top-right': ' ', 'middle-left': ' ', 'middle-middle': ' ', 'middle-right': ' ', 'bottom-left': ' ', 'bottom-middle': ' ', 'bottom-right': ' ' } def display_board(board): print(board['top-left'] + '|' + board['top-middle'] + '|' + board['top-right']) print('-+-+-') print(board['middle-left'] + '|' + board['middle-middle'] + '|' + board['middle-right']) print('-+-+-') print(board['bottom-left'] + '|' + board['bottom-middle'] + '|' + board['bottom-right']) display_board(game_state)
✅ Summary
-
Dictionaries are represented by
<span>{ }</span>, with key-value pairs separated by commas. -
Access values using
<span>myDict[key]</span>, a missing key will raise a<span>KeyError</span>. -
<span>keys()</span>,<span>values()</span>, and<span>items()</span>retrieve the keys, values, and key-value pairs of the dictionary, respectively. -
<span>get()</span>safely retrieves values, while<span>setdefault()</span>sets default values. -
<span>pprint.pprint()</span>formats and prints dictionaries. -
Dictionaries can model real-world scenarios, such as a Tic-Tac-Toe board.
📢 Interactive Question
👉 “When you first modeled with dictionaries, did you ever make a mistake in the keys that caused data to get messed up?” Share your “modeling mishap” moments in the comments, and let’s learn from each other!