liveBook · Manning

Items method

As explained in The Quick Python Book, Fourth Edition

The dictionary items method returns the dictionary's key-value pairs as iterable tuple-like items.

A dictionary’s `items()` method returns a view of its key–value pairs. Each item is a tuple containing a key and its associated value, making the method useful when you need both while iterating. section 7.2

Inspect key–value pairs

For `colors = {'red': 'rouge', 'blue': 'bleu'}`, `list(colors.items())` produces `[('red', 'rouge'), ('blue', 'bleu')]`. The `list` call converts the view for display; `items()` itself does not return a list. section 7.2

The view updates when the dictionary changes. If you need to sort the pairs, first make a list. To sort word counts by frequency rather than by word, use the value at index 1 of each tuple as the sort key. section 7.2 section 7.8.2

word_count = {}
with open("moby_01_clean.txt", "r") as infile:
    for word in infile:
        # use stip() method to remove any extra whitespace
        word = word.strip() 
 
        # increase the count for current word
        word_count.setdefault(word, 0)                   #1
        word_count[word] += 1                            #2
    
word_list = list(word_count.items())                     #3
word_list.sort(key=lambda x: x[1])                       #4
print("Most common words:")
for word in reversed(word_list[-5:]):                    #5
    print(word)
print("\nLeast common words:")
for word in word_list[:5]:
    print(word)

A word-counting example converts `items()` to a list, sorts by each tuple’s count, then selects the five most and least frequent words. section 7.8.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines the returned view, shows tuple pairs and list conversion, and applies them in a sorting workflow without examining implementation internals.
Examples
Shows translation pairs and a word-frequency program that prints the five most and least common words.
What it assumes
Assumes familiarity with dictionaries, loops, and basic list sorting; explains the distinction between a view and a list.
What you can do after
Apply it via Python’s `dict.items()` to obtain key–value pairs and sort a list of them by value.
How it connects
Connects dictionary views and tuples to for loops, lists, sorting, and word counting.

Also explained in

Compare how 2 books explain items method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.