Python Lists and Dictionaries
After completing this topic
You will be able to explain the difference between lists and dictionaries and choose the appropriate one for a given situation.
Lists β Ordered Collections
A list is a container that holds multiple values in a specific order. It is created using square brackets ([]).
fruits = ["apple", "banana", "grape"]
# Indexingprint(fruits[0]) # 'apple'print(fruits[-1]) # 'grape'
# Modificationfruits[1] = "strawberry" # ['apple', 'strawberry', 'grape']
# Addition/Deletionfruits.append("mango") # Add to the endfruits.insert(0, "watermelon") # Insert at index 0fruits.remove("grape") # Delete by valuedel fruits[0] # Delete by indexLists are mutable, meaning you can modify, add, or delete elements after they are created.
Iterating and Manipulating Lists
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
# Iterationfor n in numbers: print(n, end=" ") # 3 1 4 1 5 9 2 6
# Sortingsorted_nums = sorted(numbers) # [1, 1, 2, 3, 4, 5, 6, 9] β original list remains unchangednumbers.sort() # Sorts the original list in place
# Useful built-in functionsprint(len(numbers)) # 8print(sum(numbers)) # 31print(min(numbers)) # 1print(max(numbers)) # 9
# List comprehension β create a new list in a single linesquares = [x ** 2 for x in range(5)]# [0, 1, 4, 9, 16]List comprehension is a concise way to create new lists by condensing for loops into a single line. It's a common pattern in Python code, so it's important to become familiar with it.
Dictionaries β Key-Value Stores
Dictionaries store data as key-value pairs. They are created using curly braces ({}).
user = { "name": "Kim Hoon", "age": 30, "email": "hoon@example.com"}
# Accessing valuesprint(user["name"]) # 'Kim Hoon'print(user.get("phone")) # None (returns None instead of an error)
# Adding/Modifyinguser["phone"] = "010-1234" # Adds a new key-value pair if the key doesn't existuser["age"] = 31 # Modifies the value if the key exists
# Deletingdel user["email"]While lists use indices ("what's the first element?"), dictionaries use keys ("what's the value associated with 'name'?"). Keys are usually strings, but can also be numbers or tuples.
Iterating Through Dictionaries
scores = {"Korean": 90, "English": 85, "Math": 95}
# Iterate over keysfor subject in scores: print(subject) # Korean, English, Math
# Iterate over keys and values simultaneouslyfor subject, score in scores.items(): print(f"{subject}: {score} points")
# Iterate over values onlytotal = sum(scores.values())print(f"Total score: {total}") # 270
# Check if a key existsif "Science" in scores: print(scores["Science"])else: print("No Science score").items() returns a tuple of (key, value). .keys() returns only the keys, and .values() returns only the values.
Lists vs. Dictionaries β When to Use What
| Situation | Choice | Reason |
|---|---|---|
| Order is important (1st, 2nd, 3rd...) | List | Index-based ordering |
| Need to look up by name ("name", "age") | Dictionary | Access by key |
| Allow duplicate values | List | [1, 1, 2, 3] is valid |
| Keys must be unique | Dictionary | Overwrites if you try to insert the same key twice |
| Searching through 1 million items | Dictionary | Key lookup is O(1) vs. list search is O(n) |
A common pattern in real-world applications is a list of dictionaries. Think of it like a database table.
users = [ {"name": "Kim Hoon", "age": 30}, {"name": "Lee Soo", "age": 25}, {"name": "Park Jin", "age": 35},]
# Filter for users aged 30 or olderseniors = [u for u in users if u["age"] >= 30]JSON files, API responses, and configuration files β these are often in the form of a "list of dictionaries". If you can freely combine these two data types, you have mastered the basics of data processing in Python.