Dictionary

Dictionary Basics

All of the compound data types we have studied in detail so far — string, list — are sequential collections. This means that the items in the collection are ordered, or sequenced, and their values can be accessed with integer indices. They are ordered sets of data.

Dictionary is a different kind of collection. It's Python's built-in mapping type. A map is an unordered associative collection.

You can view a dictionary as an unordered series of key:value pairs within curly brackets:

dict = {key1: value1, key2: value2...}

Dictionary values can be of any data type, including strings, integers, objects, or even other dictionaries. Within a single dictionary, the values don't all need to be the same type. You can mix and match as needed.

Dictionary keys have more restrictions. They can be any immutable type. Strings and numbers can always be keys.

Some Notes:

  • Keys are unique. There can be no duplicate keys in the same dictionary.
  • The order of the elements in a dictionary is not important to the computer.

Use {} curly brackets to construct the dictionary:

Example:

# an empty dictionary
d0 = {}

# an dictionary with 3 key:value pairs
fruits = {'apple': 3, 'pear': 2, 'orange': 10}

results matching ""

    No results matching ""