Skip to content

Module 8 · Python Data Structures — topic 18 of 22

Dictionary keys and values

Work with a dictionary’s keys, values and items: the view objects keys(), values() and items(), looping over pairs, checking keys versus values, and finding the key with the largest value.

Beginner 10 min read·Lesson 121 of 306 in Python Programming

Learning objectives

  • Use keys(), values() and items()
  • Loop over key–value pairs
  • Search by value and find extremes

Definition

Work with a dictionary’s keys, values and items: the view objects keys(), values() and items(), looping over pairs, checking keys versus values, and finding the key with the largest value.

Introduction

A dictionary has three natural views: its keys, its values, and its key–value pairs. The methods keys(), values() and items() return these views, which you can loop over, convert to lists or use with functions such as sum() and max().

Why it matters

Reports need all the pairs, totals need the values, and validation needs the keys. Knowing which view to use makes these tasks one-liners.

Detailed explanation

keys() returns the keys, values() the values and items() (key, value) tuples, all in insertion order.

These are views, not copies: they reflect later changes to the dictionary.

Looping over a dictionary directly is the same as looping over keys().

for key, value in d.items(): unpacks each pair and is the standard way to process a dictionary.

key in d checks keys only. To search values use value in d.values().

max(d, key=d.get) returns the key whose value is largest; sorted(d.items(), key=lambda kv: kv[1]) sorts pairs by value.

Convert views with list() when you need indexing or a snapshot that won’t change.

Syntax

Text
for key in d.keys():
for value in d.values():
for key, value in d.items():
best = max(d, key=d.get)
  • keys(), values() and items() are views.
  • items() gives pairs to unpack.
  • key=d.get compares keys by their values.

Code examples

Three views

Python
stock = {"pen": 40, "pad": 12, "ink": 7}
print(list(stock.keys()))
print(list(stock.values()), sum(stock.values()))
print(list(stock.items()))
Output
['pen', 'pad', 'ink']
[40, 12, 7] 59
[('pen', 40), ('pad', 12), ('ink', 7)]

Keys versus values

Python
stock = {"pen": 40, "pad": 12}
print("pen" in stock, 40 in stock, 40 in stock.values())
view = stock.keys()
stock["clip"] = 5
print(list(view))
Output
True False True
['pen', 'pad', 'clip']

More examples

A sales summary

Python
sales = {"Mon": 1200, "Tue": 950, "Wed": 1430, "Thu": 1100}
for day, amount in sales.items():
print(f"{day}: {amount:>5}")
best = max(sales, key=sales.get)
print("Best day:", best, sales[best])
print("Average:", sum(sales.values()) / len(sales))
ranked = sorted(sales.items(), key=lambda kv: kv[1], reverse=True)
print("Ranking:", [day for day, _ in ranked])
print("Days above 1000:", [d for d, a in sales.items() if a > 1000])
Output
Mon:  1200
Tue:   950
Wed:  1430
Thu:  1100
Best day: Wed 1430
Average: 1170.0
Ranking: ['Wed', 'Mon', 'Thu', 'Tue']
Days above 1000: ['Mon', 'Wed', 'Thu']

Step-by-step explanation

  • items() gives each day with its amount for the report.
  • max(sales, key=sales.get) compares days by their amounts and returns the best day.
  • sum(sales.values()) / len(sales) computes the average.
  • sorted(...items(), key=...) ranks pairs by amount; comprehensions filter days.

Expected output

Running “A sales summary” prints exactly:

TextOutput
Mon: 1200
Tue: 950
Wed: 1430
Thu: 1100
Best day: Wed 1430
Average: 1170.0
Ranking: ['Wed', 'Mon', 'Thu', 'Tue']
Days above 1000: ['Mon', 'Wed', 'Thu']

Practical applications

  • Dashboards loop over items() to render metrics.
  • Leaderboards find the top scorer with max(scores, key=scores.get).
  • Validation code checks that required keys are present.

Best practices

  • Loop with items() when you need both key and value.
  • Use max/min with key=d.get to find extremes.
  • Convert views to lists only when needed.

Common mistakes

Searching values with in d

Avoid

if 40 in stock:

Prefer

if 40 in stock.values():

in on a dictionary checks keys only.

Indexing a view

Avoid

first_key = d.keys()[0]

Prefer

first_key = next(iter(d)) # or list(d)[0]

Views don’t support indexing.

Key takeaways

  • keys(), values() and items() are live views.
  • for k, v in d.items() loops over pairs.
  • in checks keys; use values() to search values.

Try it yourself

  1. 1
    Find the student with the lowest mark in a dictionary of marks.
  2. 2
    Print all products whose stock is below 10 using items().

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhy does {[1, 2]: "x"} raise TypeError?
Practise this topic