Skip to content

Computer Science · Ch 10 — Tuples and Dictionaries

Creating a Dictionary

10.7.1

Creating a Dictionary

To create a dictionary, write its items separated by commas and enclosed in curly braces { }. Each item is a key-value pair with the key and value separated by a colon (:).

Two rules govern what may appear on each side of the colon:

  • Keys must be unique, and each key must be of an immutable data type — a number, a string, or a tuple. (A list, being mutable, cannot be a key.)
  • Values may be repeated and can be of any data type whatsoever.

Three ways to start a dictionary

1. An empty dictionary with curly braces:

>>> d1 = {}
>>> d1
{}

2. An empty dictionary with the built-in dict() function:

>>> d2 = dict()
>>> d2
{}

3. A dictionary created with its items written out — here, mapping students' names to their marks in percentage:

>>> marks = {'Anita': 95, 'Bala': 89, 'Chetan': 92, 'Divya': 85}
>>> marks
{'Anita': 95, 'Bala': 89, 'Chetan': 92, 'Divya': 85}
``` …