Dicts Methods

The full text of this chapter, to read or revisit. To practise, do the exercises.

▶ Do the exercises

Exercise 1 — Introduction to Dictionary Methods

Python dictionaries come with several built-in methods that make it easy to access and work with their data. The three most important methods are:

- .keys() - Returns all the keys in the dictionary - .values() - Returns all the values in the dictionary - .items() - Returns all key-value pairs as tuples

Let's see these methods in details!

Exercise 2 — The .keys() Method

The .keys() method returns a view of all the keys in a dictionary. This is useful when you want to:

- Check what information is available in the dictionary - See all the field names - Prepare to iterate through keys (next chapter!)

codemon = { "name": "Pyrochu", "type": "fire", "level": 18 } keys = codemon.keys() # Get all keys print("Dictionary keys:", keys) # Convert to list if needed keys_list = list(keys) print("As a list:", keys_list)

View Objects vs Lists

The .keys() method doesn't return a regular list - it returns a special view object. This view object reflects changes to the dictionary in real-time. If you need a regular list, use list(codemon.keys()).

Exercise 3 — What Does .keys() Return?

Given the following dictionary, what will list(codemon.keys()) contain?

codemon = { "name": "Florachu", "type": "plant", "level": 12 }
Options
• ['name', 'type', 'level']
• ['Florachu', 'plant', 12]
• [('name', 'Florachu'), ('type', 'plant'), ('level', 12)]
• {'name', 'type', 'level'}

Hint : Think about what .keys() is designed to return - the keys or the values?

Exercise 4 — The .values() Method

The .values() method returns a view of all the values in a dictionary. This is useful when you want to:

- Work with just the data (ignoring the keys) - Calculate statistics on all values - Check if a specific value exists anywhere in the dictionary

codemon = { "name": "Aquachu", "type": "water", "level": 15 } values = codemon.values() # Get all values print("Dictionary values:", values) # Convert to list and check if a value exists values_list = list(values) print("Does codemon have 'water'?", "water" in values_list) print("Does codemon have level 15?", 15 in values_list)

Values Can Be Duplicates

Unlike keys (which must be unique), dictionary values can be duplicated. So .values() might return the same value multiple times if it appears in different key-value pairs.

Exercise 5 — The .items() Method

The .items() method returns a view of all key-value pairs as tuples. Each tuple contains (key, value). This is useful when you need both the key and value together.

codemon = { "name": "Pyrochu", "type": "fire", "level": 18 } items = codemon.items() # Get all key-value pairs print("Dictionary items:", items) # Convert to list to see the tuples clearly items_list = list(items) print("As a list of tuples:", items_list)

The .items() method is particularly useful for iteration (which we'll cover in the next chapter), because it gives you both pieces of information at once.

Exercise 6 — Using Dictionary Methods

Complete the code to use the appropriate dictionary methods to get all keys, all values, and all key-value pairs.

Hint : Think about which method returns keys, which returns values, and which returns both together.

Exercise 7 — The 'in' Operator with Dictionaries

The in operator checks if a key exists in a dictionary. By default, it only checks keys, not values.

codemon = { "name": "Aquachu", "type": "water", "level": 15 } # Check if keys exist print("Does 'name' key exist?", "name" in codemon) print("Does 'power' key exist?", "power" in codemon) # This checks KEYS, not values! print("Does 'Aquachu' exist?", "Aquachu" in codemon) # False! (it's a value, not a key) print("Does 'water' exist?", "water" in codemon) # False! (it's a value, not a key) # To check if a value exists, use .values() print("Does 'Aquachu' exist in values?", "Aquachu" in codemon.values())

Common Mistake

A common mistake is thinking in checks both keys and values. It ONLY checks keys by default. To check if a value exists, you must use in codemon.values().

Exercise 8 — Understanding the 'in' Operator

Given the following dictionary, what will this code print?

codemon = { "name": "Pyrochu", "type": "fire", "level": 18 } print("fire" in codemon)
Options
• False
• True
• An error will occur
• None

Hint : Remember that in checks for keys by default, not values. Is 'fire' a key or a value in this dictionary?

Exercise 9 — Match Methods with Their Purpose

Match each dictionary method or operator with what it does:

Items to match
• .keys()
• .values()
• .items()
• in
Definitions
• Returns all keys from the dictionary
• Returns all values from the dictionary
• Returns all key-value pairs as tuples
• Checks if a key exists in the dictionary

Exercise 10 — Practical Application

Complete the code to check if a Codémon has a 'moves' key, and if a specific move exists in the dictionary's values.

Hint : Think about when to use in directly versus in codemon.values() or in codemon.keys().

Exercise 11 — Challenge: Codémon Team Analysis

Analyze your Codémon's stats using dictionary methods! 1. Print all the stat names (keys) available for this Codémon 2. Print all the stat values 3. Check if the Codémon has a "speed" stat 4. Check if the value "legendary" exists anywhere in the stats 5. Print each stat with its value in a readable format using the appropriate method

Starter code
codemon = {"name": "Aquachu", "type": "water", "level": 25, "power": 85, "rarity": "rare"} print("=== CODEMON ANALYSIS ===") # 1. Print all stat names (keys) # 2. Print all stat values # 3. Check if 'speed' stat exists # 4. Check if 'legendary' value exists # 5. Print each stat with its value print("\n=== DETAILED STATS ===")
Back to the course