The Python dictionary list type

What is a dictionary in Python?

Creating a dictionary

A dictionary is pretty much how it sounds, it contains a term and then a definition, and uses curlybrackets:

myDict = { "Name"   : "John", "Role"   : "Analyst", "Age"    : 22, "Single" : False }

print myDict
Outputs: { "Age" : 22, "Role" : "Analyst", "Single" : False, "Name" : "John" }

Notice that like other lists, a dictionary can contain multiple value types, strings, integersand Booleans.

Like sets, dict’s:

  1. Cannot have the same key multiple times (a dict wouldn’t contain 2 “Name” entries)
  2. Have no specific order when printed

Selecting an item from a Dictionary

To select an item, we would use the Key rather than a number, lets use the example above:

myDict = { "Name" : "John", "Role" : "Analyst", "Age" : 22, "Single" : False }

print myDict['Name']
Outputs: John

As you can see, we have returned the value associated with the “Name” key.

Reassigning Values

You can reassign values in dictionary’s:

myDict['Name'] = 'Steve'
print myDict
Outputs: { "Age" : 22, "Role" : "Analyst", "Single" : False, "Name" : "Steve" }