liveBook · Manning

Items method

As explained in Python Workout: 50 ten-minute exercises

dict.items is the dictionary method that returns an iterator over the dictionary's key-value pairs.

When a dictionary’s keys and values must be processed together, items() supplies one key-value pair per iteration. Unpack each pair into names such as key and value, then transform or format them. section 7.27

Building attributes from keyword arguments

def myxml(tagname, content='', **kwargs): attrs = ''.join([f' {key}="{value}"' for key, value in kwargs.items()]) return f'<{tagname}{attrs}>{content}</{tagname}>' Here, kwargs.items() feeds each attribute name and value to the list comprehension, whose strings are then joined into the opening tag. section 6.2

Transforming dictionary values

A dictionary comprehension can iterate through items(), preserve each key, apply func(value), and use the result as the corresponding new value. section 7.27

def myxml(tagname, content='', **kwargs):
   attrs = ''.join([f' {key}="{value}"'
                    for key, value in kwargs.items()])
   return f'<{tagname}{attrs}>{content}</{tagname}>'

Compare the complete function with simpler versions that add a tag and content before processing keyword-argument attributes. section 6.2

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains the returned iterator, pair unpacking, and comprehensions, stopping short of implementation internals.
Examples
Demonstrates XML-like attribute generation and dictionary value transformation.
What it assumes
Assumes familiarity with dictionaries, iteration, comprehensions, and functions passed as arguments.
What you can do after
Apply it via comprehensions to build formatted strings or new dictionaries from existing key-value pairs.
How it connects
Connects dictionary iteration with keyword arguments, list comprehensions, dictionary comprehensions, string formatting, and string joining.

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 Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.