A name–value pair, also called a key–value pair, associates a key with one value inside a dictionary. Unlike sequence indexes, keys can typically be integers or strings, making associations such as usernames and user IDs easy to represent. section 5.0
Use name–value pairs when you need to:
- Store a small record or configuration, such as website details, user preferences, or file information. section 5.0
- Accumulate information over time, such as rainfall totals keyed by city. section 5.9
- Pass several named options to a function through **kwargs, where keyword names become dictionary keys. section 7.3
- Transform iterable data with a dictionary comprehension, producing a key–value pair for each item. section 8.19
Accumulate rainfall by city
Treat the city as the key and the rainfall amount as the value. Retrieve the existing amount with dict.get(city_name, 0), convert input to int, and assign the updated pair: rainfall[city_name] = rainfall.get(city_name, 0) + mm_rain. Converting matters because input returns strings; adding strings concatenates them instead of adding numbers. section 5.9
try:
mm_rain = int(input('Enter mm rain: '))
except ValueError:
print('You didn't enter a valid integer; try again.')
continue
rainfall[city_name] = rainfall.get(city_name, 0) + mm_rain
Inspect the complete rainfall update, including integer conversion, invalid-input handling, and assignment of the accumulated pair. section 5.9
def myxml(tagname, content='', **kwargs):
attrs = ''.join([f' {key}="{value}"'
for key, value in kwargs.items()])
return f'<{tagname}{attrs}>{content}</{tagname}>'
Inspect how keyword name–value pairs become XML attributes through **kwargs, items(), and a comprehension. section 7.3










