Informatics Practices · Ch 4 — Working with Lists and Dictionaries
Creating a Dictionary
4.6.1
Creating a Dictionary
A dictionary is written between curly braces { }, with the items separated by commas, and each item written as a key-value pair with a colon (:) between the key and its value. This is the piece of syntax that distinguishes a dictionary at a glance from a list (square brackets) or a tuple (parentheses).
The rules for what may go inside are not symmetric between keys and values:
- Keys must be unique. No two items in a dictionary may carry the same key — the key is the handle by which a value is found, so a duplicate key would be ambiguous.
- Keys must be of an immutable data type — a number, a string, or a tuple. A mutable type such as a list cannot serve as a key.
- Values are unrestricted. They can be of any data type, and the same value may appear in the dictionary any number of times.
The simplest dictionary is an empty one — a pair of curly braces with nothing inside:
>>> dict1 = {} # dict1 is an empty dictionary
>>> dict1
{}
A more useful example maps names of students to their marks in percentage. Each name (a string, hence immutable) is a key; the marks are the values:
>>> dict3 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
>>> dict3
{'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
``` …