Python Dictionaries

Python Dictionaries

Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered*, changeable, and does not allow duplicates.

* As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

Dictionaries are written with curly brackets {}, and have keys and values:

Create a Dictionary

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(thisdict)

Accessing and Changing Items

You can access the items of a dictionary by referring to its key name, inside square brackets.

Accessing and Updating

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

// Accessing the model x = thisdict["model"] print(x) // Mustang

// Changing the year thisdict["year"] = 2018 print(thisdict["year"]) // 2018


Dictionary Methods

Dictionaries have several useful built-in methods:


Adding and Removing Dictionary Items

You can easily add new key:value pairs by assigning a value to a new key. To remove items, you can use the pop() or del keywords.

Add and Remove Example

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

// Adding an item thisdict["color"] = "red"

// Removing an item thisdict.pop("model")

print(thisdict)


Nested Dictionaries

A dictionary can contain dictionaries, this is called nested dictionaries. They are very useful for storing complex data structures.

Nested Dictionary Example

myfamily = {
  "child1" : {
    "name" : "Emil",
    "year" : 2004
  },
  "child2" : {
    "name" : "Tobias",
    "year" : 2007
  }
}

print(myfamily["child2"]["name"]) // Output: Tobias


Exercise

?

How is data structured inside a Python dictionary?