liveBook · Manning

Name-value pair

As explained in Python Workout: 50 ten-minute exercises

A name-value pair is a data association in which an identifying name or key corresponds to a value.

When a program needs to associate a username with an ID, a hostname with an IP address, or an option with its setting, use a name-value pair: an identifying key points to its corresponding value. Python dictionaries store these associations, allowing retrieval by meaningful keys instead of integer indexes. section 4.0

A dictionary makes name-value pairs useful for several common jobs:

  • Store a small record, such as configuration options, file information, or user preferences. section 4.0
  • Keep related values together instead of scattering them across separate variables, then pass them through a program as one object. section 4.0
  • Accumulate results over time, such as word counts or other measurements keyed by descriptive names. section 5.12

Looking up a value by name

A menu can associate product names with prices: menu = {'coffee': 3, 'sandwich': 8} order = input('Order: ').strip() if order in menu: print(f'Total: ${menu[order]}') else: print('That product is not in stock.') The key is the product name and the value is its price. The in operator checks keys, while menu[order] retrieves the associated value. This is more natural than searching a list of lists or tuples. section 4.4

Python implements dictionary lookup with hashing. A hash function maps a key to a storage location, enabling fast key lookup and ensuring key uniqueness; it does not provide the same guarantee for finding values. The model omits implementation details, including changes associated with Python 3.6. section 4.1

Figure 5.2 Initialized counts in the dict

An initialized counts dictionary provides a compact visual example of descriptive names associated with values before a file-processing task updates them. section 5.12

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains keys, values, dictionary lookup, and hashing, but defers detailed implementation changes and internals.
Examples
Demonstrates menus, word-count dictionaries, configuration files, city populations, and transformed name-hobby data.
What you can do after
Apply it via Python dictionaries and comprehensions to store, retrieve, transform, and accumulate associated data.
How it connects
Connects name-value pairs with dictionaries, hash functions, sets, comprehensions, configuration files, and JSON data.

Also explained in

Compare how 11 books explain name-value pair →

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.