Python Dictionary

Dictionaries are used to store key-value pairs in Python. Dictionaries are similar to lists, both store a collection of values. However, unlike lists, you need a key to access an item in dictionary. In lists, index is used to access an item.

Items of a dictionary are typed within curly braces {} separated by commas. Each item in a dictionary consists of a key-value pair. Keys and values are separated by a colon (:).

car = {"make" : "ACME", "model" : "Roadster", 
       "year" : 1972, "color" : "Red"}

# car[Key]      -> Value
# car["make"]   -> ACME
# car["model"]  -> Roadster
# car["year"]   -> 1972
# car["color"]  -> Red

Accessing Items in a Dictionary

To access a value in a dictionary, type its key name in square brackets.

myCar = {"make" : "ACME", "model" : "Roadster", 
         "year" : 1972, "color" : "Red"}

print("Make and model of my car is : " 
      + myCar["make"] + " " + myCar["model"])

# Make and model of my car is : ACME Roadster

Updating Items in a Dictionary

To update an item in a dictionary, type item’s key value in square brackets [].

myCar = {"make": "ACME", "model": "Cougar",
         "year": 1972, "color": "Red"}

myCar["make"]  = "Ford"
myCar["model"] = "Cougar"

# Dictionary is updated as :
# {"make" : "Ford", "model" : "Cougar",
#  "year" : 1972, "color" : "Red"}

Iterating a Dictionary

Using a for loop you can iterate keys in a dictionary. To access values for these keys, type the key inside square brackets.

Note that str() built-in function is used in the following code, since not all values are string in myCar object. Year of car (1972) has an integer data type. If you don’t use str() function, it will throw a TypeError.

myCar = {"make" : "ACME", "model" : "Roadster",
         "year" : 1972, "color" : "Red"}

for x in myCar:
   print(x + " -> " + str(myCar[x]))

# make -> Ford
# model -> Cougar
# year -> 1972
# color -> Red

You can also use items() method of dictionary to iterate both keys and values in a dictionary.

myCar = {"make" : "ACME", "model" : "Roadster",
         "year" : 1972, "color" : "Red"}

for key, value in myCar.items():
   print(key + " -> " + str(value))
   
# make -> Ford
# model -> Cougar
# year -> 1972
# color -> Red

Adding Items

To add a new item to dictionary, you can use brackets notation. Type the key inside brackets and assign it a value.

myCar = {"make" : "ACME", "model" : "Roadster",
         "year" : 1972}

myCar["color"] = "red"

# {"make" : "ACME", "model" : "Roadster", 
#  "year" : 1972, "color" : "red"}

Removing Items

You can use pop() method to remove an item from a dictionary.

myCar = {"make" : "ACME", "model" : "Roadster", 
         "year" : 1972, "color" : "red"}

myCar.pop("color")

# {"make" : "ACME", "model" : "Roadster",
#  "year" : 1972}

You can also use del statement.

myCar = {"make" : "ACME", "model" : "Roadster",
         "year" : 1972, "color" : "red"}

del myCar["color"]

# {"make" : "ACME", "model" : "Roadster", 
#  "year" : 1972}

Using clear() method you can remove all items from a dictionary.

myCar = {"make" : "ACME", "model" : "Roadster", 
         "year" : 1972, "color" : "red"}

myCar.clear();

# {}

del statement can be used to delete dictionary object itself.

myCar = {"make" : "ACME", "model" : "Roadster",
         "year" : 1972, "color" : "red"}

del myCar

Checking Whether a Key Exists

The in operator is used to check whether a key exists in a dictionary. Dictionary’s keys() method is used to search in keys.

phoneBook = {
    "George" : "(450)856-6856",
    "Anne"   : "(242)426-9729",
    "Joe"    : "(302)893-2316"
}

if "Anne" in phoneBook.keys():
    print("name exists in phone book.")

Checking Whether a Value Exists

Similarly in operator is used to check whether a value exists in a dictionary. Instead of keys() method, dictionary’s values() method is used to search in values.

phoneBook = {
    "George" : "(450)856-6856",
    "Anne"   : "(242)426-9729",
    "Joe"    : "(302)893-2316"
}

if "(302)893-2316" in phoneBook.values():
    print("number exists in phone book.")
SHARE