liveBook · Manning

Dict()

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

dict() is the Python built-in constructor that creates a dictionary from supplied arguments or creates an empty dictionary when called without arguments.

dict() creates a dictionary. Called without arguments, it returns an empty dictionary; called with keyword arguments, it creates key/value pairs without quoting the keys. section 4.1.1

Build a dictionary of answers

answers = dict(name='Sir Lancelot', quest='To seek the Holy Grail', favorite_color='blue') print(answers) # {'name': 'Sir Lancelot', 'quest': 'To seek the Holy Grail', 'favorite_color': 'blue'} The equivalent literal is {'name': 'Sir Lancelot', 'quest': 'To seek the Holy Grail', 'favorite_color': 'blue'}. Add later entries with square brackets, such as answers['quest'] = 'To seek the Holy Grail'. section 4.1.1

dict() also converts an iterable of two-item pairs into a dictionary. Combining headers and values with zip() makes it useful for turning manually parsed CSV rows into records. section 19.1.2

Convert headers and a row

headers = ['exercise', 'reps'] line = ['Burpees', '20-50'] record = dict(zip(headers, line)) print(record) # {'exercise': 'Burpees', 'reps': '20-50'} section 19.1.2

>>> rec = dict(zip(headers, line))
>>> rec
{'exercise': 'Burpees', 'reps': '20-50'}

Inspect the compact REPL transformation from paired headers and values to one dictionary record. section 19.1.2

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Explains empty, keyword, and pair-based construction with runnable examples, while deferring dictionary internals.
Examples
Uses knights’ answers, exercise CSV rows, REPL checks, list comprehensions, and map().
What you can do after
Apply it via Python to build mappings from named values or paired sequences.
How it connects
Links dictionaries with dictionary literals, zip(), dict.items(), CSV parsing, and pprint.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.