Fundamentals 7 min read

Python Lists & Dictionaries: Master Key Data Structures in 5 Minutes

This tutorial walks you through the essential operations of Python lists and dictionaries, demonstrates combined usage, highlights four common pitfalls with fixes, and provides quick hands‑on exercises so you can store and manipulate data efficiently in just five minutes.

liandk
liandk
liandk
Python Lists & Dictionaries: Master Key Data Structures in 5 Minutes

1. List (list): batch data container

Core idea: a list can store any type of data (numbers, strings), is mutable, iterable, and is the most frequently used data structure.

# 1. Define a list (using [] and commas)
scores = [88, 95, 70, 66, 92]  # store grades
names = ["张三", "李四", "王五"]  # store names
mix = [18, "Python", 62.5, True]  # mixed types are allowed

# 2. Core operations (use directly, must master)
print(scores[0])               # get first element, outputs: 88
scores.append(85)               # add element, result: [88, 95, 70, 66, 92, 85]
scores.remove(70)               # delete specific element, result: [88, 95, 66, 92, 85]
scores[2] = 75                 # modify element, result: [88, 95, 75, 92, 85]
print(len(scores))              # view length, outputs: 5

# 3. Combine with for‑loop for high‑frequency practice
for name in names:
    print("姓名:", name)
for s in scores:
    if s >= 80:
        print(s, "合格")

2. Dictionary (dict): key‑value storage for precise lookup

Core idea: each key maps to a value, forming a one‑to‑one correspondence, similar to a phone book (name → phone).

# 1. Define a dictionary (using {} and colon)
student = {
    "name": "张三",
    "age": 18,
    "score": 88,
    "is_student": True
}

# 2. Core operations (use directly, must master)
print(student["name"])          # fetch by key, outputs: 张三
student["score"] = 90            # modify value, score becomes 90
student["gender"] = "男"       # add new key‑value pair
del student["is_student"]       # delete a key‑value pair

# 3. Iterate over a dictionary (two common ways)
# Way 1: iterate over all keys
for key in student:
    print(key, ":", student[key])
# Way 2: iterate over key‑value pairs (more concise)
for key, value in student.items():
    print(key, ":", value)

3. Combined practice: list of dictionaries

# Store multiple students (list of dicts)
students = [
    {"name": "张三", "age": 18, "score": 88},
    {"name": "李四", "age": 19, "score": 95},
    {"name": "王五", "age": 17, "score": 76}
]

# Iterate and print "name + score", check pass/fail
for stu in students:
    name = stu["name"]
    score = stu["score"]
    if score >= 60:
        print(f"{name},成绩:{score},及格")
    else:
        print(f"{name},成绩:{score},不及格")

4. Four common pitfalls for beginners (with solutions)

❌ Pitfall 1: List index out of range (e.g., scores[10] when list has 5 elements). Solution: Index must be within 0‑(len(list)‑1); use len(list) to check length first.

❌ Pitfall 2: Dictionary key error (e.g., student["phone"] when key does not exist). Solution: Use dict.get("phone", "无此键") for safe lookup.

❌ Pitfall 3: Incorrect modification syntax (assigning to a list with =, or using unquoted Chinese keys in a dict). Solution: Modify lists with append / remove /index assignment; dict keys must be quoted strings.

❌ Pitfall 4: Installing packages via Alibaba or Douban mirrors fails with "webpage parsing error". Solution: Switch to alternative mirrors, preferably Tsinghua's (

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple 包名

) or USTC's as backup.

5. Post‑lesson mini‑tasks (5‑minute copy‑and‑run)

# 1. List: define 5 numbers, add one, remove one, print final list
nums = [10, 20, 30, 40, 50]
nums.append(60)
nums.remove(30)
print(nums)

# 2. Dictionary: store personal info, modify weight, print all pairs
my_info = {"name": "Your Name", "age": 25, "weight": 70}
my_info["weight"] = 68
for k, v in my_info.items():
    print(k, ":", v)

# 3. List of dictionaries: store two classmates, print name and score
classmates = [
    {"name": "同学1", "score": 85},
    {"name": "同学2", "score": 92}
]
for classmate in classmates:
    print(classmate["name"], "成绩:", classmate["score"])

6. Key takeaways

Lists enable batch data storage; dictionaries provide precise key‑value mapping—both are foundations for later practical scenarios such as office automation and web crawling.

Essential skills to master today: list append / remove /index assignment, dictionary get/modify/iterate, and nesting lists within dictionaries.

When errors occur, first check list indices, dictionary keys, and package‑install mirrors (prefer Tsinghua or USTC mirrors over Alibaba/Douban).

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonData Structurestutoriallistdictionarybeginners
liandk
Written by

liandk

Seasoned Java and mobile developer with years of experience, specializing in mini‑programs, public accounts, and full‑stack front‑end development. In the AI era, I continuously learn to broaden my knowledge and evolve. I revived a public account I started a decade ago during a dessert‑startup venture, using code as a vessel and knowledge as a companion. I share personal projects, technical articles, programming tips, and growth insights—let’s improve together and set sail.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.