Python – Dictionary

Dictionary in Python

In this lesson you will learn how to use Python Dictionary. We would cover the following topics.

    1. Introduction to Python Dictionary
    2. Creating a Dictionary
    3. Accessing Values in a Dictionary
    4. Modifying a Dictionary
    5. Dictionary Functions in Python
    6. Dictionary Methods in Python
    7. Watch the Video

 

1. Introduction to Python Dictionary

A dictionary is Python store items the way a normal dictionary stores item. In each entry, you have two things: a key and a value. That is why we say, dictionary stores key-value pairs. The key and its value is separated using color (:). Then each entry is separate from the other by a comma. Also a python dictionary is created using curly braces { }.

While the keys in a dictionary are unique, the values are not. So key in a dictionary are immutable.

 

2. Creating in a Dictionary

Unlike the list and tuples, you create  dictionary using curly braces. Then you use comma to separate each key-value pair in the dictionary.

student = {
    "name": "Emily William",
    "Location": "Nigeria",
    "Score" : 89,
    "Grade" : 'A',
    "Address" : "No 21 Bills Street"
}

The code above creates a dictionary named student. This represents the record of a particular student.

 

 

3. Accessing Values in Dictionary

How can we access values in a dictionary? Unlike lists and tuples that use indexes, dictionary uses key. So you specify the key to access the value. Let’s use a typical example of a dictionary containing the days of the week.

This is shown below.

daysOfWeek = {
    1 : "Monday",
    2 : "Tuesday",
    3 : "Wednesday",
    4 : "Thursday",
    5 : "Friday",
    6 : "Saturday",
    7 : "Sunday"  
}

To access the values (given as strings) we used the keys (given as numbers). So look at the code below. What do you think the output would be?

print(“Today is “ + daysOfWeek[1])
print(“Tomorrow is “ + daysOfWeek[2])

 

The output would be:

Today is Monday
Tomorrow is Tuesday

Note that we can only access values using keys that exist in the dictionary. For example we cannot day daysOfWeek(8). This would result in an error because there is not 8 in the dictionary.

 

 

4. Modifying a Dictionary

Remember we cannot modify the keys. We can only modify the values. These we can do in three ways:

  • add new entry
  • update the value of an entry
  • delete an entry

 

Add new entry

To add a new entry into a dictionary, you use that add method of the dictionary. So  to add an entry Nationality and Language to the original dictionary we created, we can say:

student["Nationality"] = "American"
student["Language"] = "English"

 

Update value of an entry

To update and entry you simply assign another value to the key of the entry you want to update. The following would update the name and address of the student:

student["Name"] = "Emily Normal William"
student["Address"] = "25 Western Avenue 1104 BP"


Delete an entry

To delete an entry from a dictionary, you use the del keyword. Example is given below:

del student["Location"]

Note that the above code would delete both the key and the value.

 

 

5. Dictionary Functions in Python

Python provides a number of useful functions you can use with dictionaries. These functions are given in the table below. I recommend you take some time to practice them.

SN. Function and brief description
1 cmp(dict1, dict2): Compares elements of both dict but has been removed in Python 3.
2 len(dict): Returns the total length of the dictionary. This is the same as the number of items in the dictionary.
3 str(dict): Returns a printable string representation of  the dictionary
4 type(variable): Gives the type of the variable passed. If the  passed variable is a dictionary, then it would return a dictionary type.

Python includes following dictionary method

 

 

6. Dictionary Methods in Python

Python provides a number of useful methods you can use with dictionaries. These methods are given in the table below. I recommend you take some time to practice them. The video below this page can help you.

SN Methods and brief description
1 dict.clear(): Deletes all elements of dictionary dict
2 dict.copy(): Returns another copy of dictionary dict
3 dict.fromkeys(): Create a new dictionary with keys from seq and values set to value.
4 dict.get(key, default=None): For the given key key, returns value or default if key not in dictionary
5 dict.has_key(key): Returns true if key in dictionary dict. Returns false if otherwise
6 dict.items(): Returns a list of the entries in a dictionary as (key, value) tuple pairs
7 dict.keys(): Returns list of all the dictionary dict’s keys
8 dict.setdefault(key, default=None): Similar to get(), but will set dict[key]=default if key is not already in dict
9 dict.update(dict2): Adds dictionary dict2‘s key-values pairs to dict
10 dict.values(): Returns list of dictionary dict‘s values

7. Watch the Video