Python Basics

Python Dictionaries

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.

Create a Dictionary

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

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

Access Items

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

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

Change Values

You can change the value of a specific item by referring to its key name:

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

Add Items

Adding an item to the dictionary is done by using a new index key and assigning a value:

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

Remove Items

There are several methods to remove items from a dictionary:

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