Python - tutorial - 07/14

dictionaries

Revision:


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.
Dictionaries are written with curly brackets, and have keys and values.

Example 1: create and print a dictionary:

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

Dictionary items: dictionary items are ordered, changeable, and does not allow duplicates. Dictionary items are presented in key:value pairs, and can be referred to by using the key name.

Example 2: print the "brand" value of the dictionary:

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

Ordered or Unordered?: as of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered. When we say that dictionaries are ordered, it means that the items have a defined order, and that order will not change. Unordered means that the items do not have a defined order, you cannot refer to an item by using an index.

Changeable: dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.

Duplicates not allowed: dictionaries cannot have two items with the same key.

Example 3: duplicate values will overwrite existing values:

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

Dictionary length: to determine how many items a dictionary has, use the len() function.

Example 4: print the number of items in the dictionary:

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

Dictionary items - data types: the values in dictionary items can be of any data type.

Example 5: string, int, boolean, and list data types:

        thisdict = {
            "brand": "Ford",
            "electric": False,
            "year": 1964,
            "colors": ["red", "white", "blue"]
        }
        print(thisdict)   # {'brand': 'Ford', 'electric': False, 'year': 1964, 'colors': ['red', 'white', 'blue']}
    

type(): from Python's perspective, dictionaries are defined as objects with the data type 'dict'.

Example 6: print the data type of a dictionary:

        thisdict = {
            "brand": "Ford",
            "model": "Mustang",
            "year": 1964
        }
        print(type(thisdict)) # class 'dict'
    

Python collections (arrays): There are four collection data types in the Python programming language:

"List" is a collection which is ordered and changeable. Allows duplicate members.
"Tuple" is a collection which is ordered and unchangeable. Allows duplicate members.
"Set" is a collection which is unordered and unindexed. No duplicate members.
"Dictionary" is a collection which is ordered and changeable. No duplicate members.


Python - access dictionary items

Accessing items: you can access the items of a dictionary by referring to its key name, inside square brackets or by using the get() method.

Example 7: get the value of the "model" key:

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

Example 8: get the value of the "model" key:

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

Get keys: the keys() method will return a list of all the keys in the dictionary.

Example 9: get a list of the keys:

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

The list of the keys is a view of the dictionary, meaning that any changes done to the dictionary will be reflected in the keys list.

Example 10: add a new item to the original dictionary, and see that the keys list gets updated as well:

        car = {
            "brand": "Ford",
            "model": "Mustang",
            "year": 1964
        }
        x = car.keys()
        print(x) #before the change # dict_keys(['brand', 'model', 'year'])
        car["color"] = "white"
        print(x) #after the change # dict_keys(['brand', 'model', 'year', 'color'])
    

Get values: the values() method will return a list of all the values in the dictionary.

Example 11: get a list of the values:

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

The list of the values is a view of the dictionary, meaning that any changes done to the dictionary will be reflected in the values list.

Example 12: make a change in the original dictionary, and see that the values list gets updated as well:

        car = {
            "brand": "Ford",
            "model": "Mustang",
            "year": 1964
        }
        x = car.values()
        print(x) #before the change # dict_values(['Ford', 'Mustang', 1964])
        car["year"] = 2020
        print(x) #after the change  dict_values(['Ford', 'Mustang', 2020])
    

Example 13: add a new item to the original dictionary, and see that the values list gets updated as well:

        car = {
            "brand": "Ford",
            "model": "Mustang",
            "year": 1964
        }
        x = car.values()
        print(x) #before the change # dict_values(['Ford', 'Mustang', 1964])
        car["color"] = "red"
        print(x) #after the change  # dict_values(['Ford', 'Mustang', 1964, 'red'])
    

Get items: the items() method will return each item in a dictionary, as tuples in a list.

Example 14: get a list of the key:value pairs

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

The returned list is a view of the items of the dictionary, meaning that any changes done to the dictionary will be reflected in the items list.

Example 15: make a change in the original dictionary, and see that the items list gets updated as well:

        car = {
            "brand": "Ford",
            "model": "Mustang",
            "year": 1964
        }
        x = car.items()
        print(x) #before the change # dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
        car["year"] = 2020
        print(x) #after the change # dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 2020)])
    

Example 16: add a new item to the original dictionary, and see that the items list gets updated as well:

        car = {
            "brand": "Ford",
            "model": "Mustang",
            "year": 1964
        }
        x = car.items()
        print(x) #before the change # dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
        car["color"] = "red"
        print(x) #after the change # dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964), ('color', 'red')])
    

Check if key exists: to determine if a specified key is present in a dictionary use the "in" keyword.

Example 17: check if "model" is present in the dictionary:

        thisdict = {
            "brand": "Ford",
            "model": "Mustang",
            "year": 1964
        }
        if "model" in thisdict:
            print("Yes, 'model' is one of the keys in the thisdict dictionary")
    


Python - change dictionary items

Change values: you can change the value of a specific item by referring to its key name.

Example 18: change the "year" to 2018:

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

Update dictionary: the update() method will update the dictionary with the items from the given argument. The argument must be a dictionary or an iterable object with key:value pairs.

Example 19: update the "year" of the car by using the update() method:

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


Python - add dictionary items

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

Example 20: add item

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

Update dictionary: the update() method will update the dictionary with the items from a given argument. If the item does not exist, the item will be added. The argument must be a dictionary, or an iterable object with key:value pairs.

Example 21: add a color item to the dictionary by using the update() method:

        thisdict = {
            "brand": "Ford",
            "model": "Mustang",
            "year": 1964
        }
        thisdict.update({"color": "red"}) # {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
    


Python - remove dictionary items

Removing items: There are several methods to remove items from a dictionary.

The pop() method removes the item with the specified key name.
The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead).
The "del" keyword removes the item with the specified key name. The "del" keyword can also delete the dictionary completely.
The clear() method empties the dictionary.

Example 22: the pop() method removes the item with the specified key name:

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

Example 23: the popitem() method removes the last inserted item

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

Example 24: the "del" keyword removes the item with the specified key name:

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

Example 25: the clear() method empties the dictionary:

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


Python - loop dictionaries

Loop through a dictionary: you can loop through a dictionary by using a "for" loop. When looping through a dictionary, the return value are the keys of the dictionary, but there are >methods to return the values as well.

Example 26: print all key names in the dictionary, one by one:

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

Example 27: rint all values in the dictionary, one by one:

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

Example 28: you can also use the values() method to return values of a dictionary:

        thisdict =	{
            "brand": "Ford",
            "model": "Mustang",
            "year": 1964
        }
        for x in thisdict.values():
            print(x)
    

Example 29: you can use the keys() method to return the keys of a dictionary:

        thisdict =	{
            "brand": "Ford",
            "model": "Mustang",
            "year": 1964
        }
        for x in thisdict.keys():
            print(x)
    

Exampless 30: loop through both keys and values, by using the items() method:

        thisdict =	{
            "brand": "Ford",
            "model": "Mustang",
            "year": 1964
        }
        for x, y in thisdict.items():
            print(x, y) # brand Ford model Mustang year 1964
    


Python - copy dictionaries

Copy a dictionary: there are ways to make a copy.

One way is to use the built-in Dictionary method copy().
Another way to make a copy is to use the built-in function dict().

Exampless 31: make a copy of a dictionary with the copy() method:

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

Exampless 32: make a copy of a dictionary with the dict() function:

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


Python - nested dictionaries

Nested dictionaries: a dictionary can contain dictionaries, this is called nested dictionaries.

Exampless 33: create a dictionary that contain three dictionaries:

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

Or, if you want to add three dictionaries into a new dictionary:

Exampless 34: create three dictionaries, then create one dictionary that will contain the other three dictionaries:

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


Python dictionary methods

Dictionary methods: Python has a set of built-in methods that you can use on dictionaries.

Method - Description
clear() - Removes all the elements from the dictionary
copy() - Returns a copy of the dictionary
fromkeys() - Returns a dictionary with the specified keys and value
get() - Returns the value of the specified key
items() - Returns a list containing a tuple for each key value pair
keys() - Returns a list containing the dictionary's keys
pop() - Removes the element with the specified key
popitem() - Removes the last inserted key-value pair
setdefault() - Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
update() - Updates the dictionary with the specified key-value pairs
values() - Returns a list of all the values in the dictionary