codescracker
python

Python Dictionary



Dictionary in Python is a data type, a kind of mapping type, which is used when we need to store multiple items in the form of key:value pairs.

In real world, you can consider any dictionary book where the information stored in the form of key:value pair, where key refers the word, and the value refers to its definition.

Dictionary helps in organizing the information. For example, in dictionary book, all the words are organized in alphabetical order, so that we can easily find the required word and get the definition or description about that word, very easily.

Note - Dictionary in Python is an ordered and changeable (mutable) collection of items, where duplicates aren't allowed.

Create a Dictionary in Python

In Python, a dictionary is created in key and value pairs, where there is a colon (:) in between key and value, and comma (,) in between every items. Each item contains a key and its value. Also the whole items must be enclosed within a curly braces, i.e. {}. Here is the syntax to create a dictionary in Python:

mydict = {key_1: val_1, key_2: val_2, ..., key_n: val_n}

Here key_1, key_2, key_n are keys, whereas val_1, val_2, val_n are values. Here is a simple example of dictionary:

mydict = {"Day": "Wednesday", "Month": "October"}
print(mydict)

The output produced by above Python program on dictionary, is shown in the snapshot given below:

dictionary in python

You're seeing the whole dictionary on output. To access and print particular value of a particular key, then you need to use mydict[key]. You'll learn all about accessing keys, values or items of a dictionary, later on, in this article.

Important - While creating a dictionary, always keep in mind, keys of the dictionary must be a single element, whereas values may be a single element such as an integer, string etc., or a multiple elements such as a list, tuple etc.

Note - The colon (:) is not required in between key and value, when creating dictionary with each items in pairs. We'll see the example on it, later on, in this tutorial.

Create Dictionary with Multiple Key's Type

The data type of all keys of a single dictionary may be the same or different. Here is an example, uses multiple types of keys:

my_dictionary = {1: "Python", "city": "New York City"}

See the first key, that is 1 is of integer type, where as the second key, that is city is of string type.

Create Dictionary with Multiple Values for a Single Key

As already said as Important notice, that the value of a single key in a dictionary may be a single or multiple values. Here is an example, assigns multiple values to a key named Marks.

my_dictionary = {"Name": "Luis", "Marks": [89, 96, 73]}

In above statement, [89, 96, 73] is basically a list of three elements (numbers), and this list is the value of a key named Marks.

Create an Empty Dictionary

To create an empty dictionary, don't add any key and value pares inside the curly braces. Here is an example to create an empty dictionary in Python:

my_dictionary = {}

An empty dictionary can also be created using the dict() method, as shown below:

my_dictionary = dict()

Create Dictionary using dict() Method

A dictionary can also be created using the dict() method. Here is an example:

my_dictionary = dict({"Name": "Jonah", "Marks": [89, 93, 97]})
print(my_dictionary)

The output produced by above program will be:

{'Name': 'Jonah', 'Marks': [89, 93, 97]}

Create Dictionary with Each Items in Pairs

While creating dictionary in which each items are in pairs, then we do not need to use colon (:) to separate key and value. Also there is no need of curly braces too. Here is an example, shows how to create a dictionary with each items in pairs.

my_dictionary = dict([("Name", "Jonah"), ("Marks", [89, 93, 97])])
print(my_dictionary)

The output produced by this program, will exactly be same as of previous program.

Create Nested Dictionary

A dictionary can also be nested inside another. Here is an example of nested dictionary in Python:

my_dictionary = {"College": "Harvard University", "Program": "Computer Science",
                 "Student": {"Name": "Nathaniel", "Address": "1549 Scott Center Rd Sherman, New York(NY)",
                             "Marks": [97, 98, 85]}}
print(my_dictionary)

The output produced by above Python program on creating a nested dictionary is:

{'College': 'Harvard University', 'Program': 'Computer Science', 'Student': {'Name': 'Nathaniel', 'Address': '1549 Scott Center Rd Sherman, New York(NY)', 'Marks': [97, 98, 85]}}

In above program, the values of key named Student is itself a dictionary, in which there are three items.

Access Dictionary Keys or Values or Items in Python

This section is important one, shows how to access only keys or only values or the whole items of a dictionary. Let's start with accessing values of a dictionary using its key.

Access Value from a Dictionary by its Key

A Value from a dictionary using its key can be accessed. Here is the syntax:

my_dictionary[key];

where key is the name of key, whose value is going to be accessed. For example:

mydict = {"Day": "Wednesday", "Month": "October"}
print(mydict["Day"])
print(mydict["Month"])

The snapshot given below shows the sample output produced by above program:

accessing dictionary values python

The question is, what if the key whose value is going to access, is not available in the dictionary ?
Let's find out using the program given below, that access a key from the dictionary, that is not available:

mydict = {"Name": "Jonah", "City": "Tacoma"}
print(mydict["Marks"])

Since the key named Marks is not available in the dictionary named mydict, therefore above program produced/raised an error as shown in the snapshot given below:

python dictionary program

Since the error raised is KeyError, therefore to handle this error, we need to use try-except block as shown in the example given below:

mydict = {"Name": "Jonah", "City": "Tacoma"}
try:
    print(mydict["Marks"])
except KeyError:
    print("\nThe key named \"Marks\" is not available!")

Now the output will be:

The key named "Marks" is not available!

The get() method can also be used to access dictionary's values using keys, as shown in the example given below:

mydict = {"Day": "Wednesday", "Month": "October"}
print(mydict.get("Day"))
print(mydict.get("Month"))

The output will be same as of previous program's output.

Note - Using get() method to access an unavailable key of a dictionary, for example, print(mydict.get("Marks")) produces None.

Access Nested Dictionary Values

To access nested dictionary values in Python, we need to nest keys. Here is the syntax to access value available in a nested dictionary:

my_dictionary[key_one][key_two]

The above code returns the value of key named key_two. The key_two is one of the key available inside a nested dictionary, which is the value of a key named key_one. Here is an example, of accessing values available in nested dictionary:

my_dictionary = {"College": "Harvard University", "Program": "Computer Science",
                 "Student": {"Name": "Nathaniel", "Address": "1549 Scott Center Rd Sherman, New York(NY)",
                             "Marks": [97, 98, 85]}}
print(my_dictionary["Student"]["Address"])

The above program displays the values of key named Address of key named Student. Here is the output:

1549 Scott Center Rd Sherman, New York(NY)

Print All Keys of Dictionary

Sometime we need to see the name of all keys available in a dictionary. Therefore, here is the code, I've created, that list out and prints all keys of a dictionary named mydict:

mydict = {"Name": "Jonah", "City": "Forks"}
for d in mydict:
    print(d)

Here is its sample output:

Name
City

Print All Values of Dictionary

Most of the time, we need to see all values of dictionary, except the whole dictionary. Therefore, here is the program, I've created, shows how to access and print all values of a dictionary in Python:

mydict = {"Name": "Jonah", "City": "Forks"}
for i in mydict:
    print(mydict[i])

Here is its sample output:

Jonah
Forks

The above program can also be replaced with following program. This program uses values() method to do the same task, of printing all dictionary values:

mydict = {"Name": "Jonah", "City": "Forks"}
for i in mydict.values():
    print(i)

This program produces exactly same output as of previous one.

Print Keys and Values of Dictionary

This is the program, I think everyone need to get, while learning dictionary in Python. Because, getting and printing all keys and values of a dictionary in manual way is needed most of the time. Therefore, I've created a program, that shows how to print keys and values of a dictionary without its default format, by manually formatted output:

mydict = {"Name": "Jonah", "City": "Tacoma"}

print("Key\t\t\t Value")
print("----------------------")
for i in mydict:
    print(i, "\t\t", mydict[i])

The output produced by above program will be:

python print dictionary key value

Print All Items of Dictionary

This program prints all items of a dictionary, using items() method. Let's take a look at the program given below:

mydict = {"Name": "Mark", "Program": "Computer Science", "Age": 22}
for i in mydict.items():
    print(i)

The output produced by above program will be:

('Name', 'Mark')
('Program', 'Computer Science')
('Age', 22)

The first element of each item indicates to key, whereas the second element of each items indicates to value.

Also, we can print both keys and values of dictionary using the same technique as done in above program. Here is the program, that prints both keys and values of dictionary in manual format:

mydict = {"Name": "Mark", "Program": "Computer Science", "Age": 22}
for i, j in mydict.items():
    print(i, "->", j)

The output produced by this Python program will be:

python print dictionary items

Add New Item to a Dictionary in Python

To add a new item to a dictionary, here is the syntax:

my_dictionary[key] = value

Or use update() method to add a new item to the dictionary. Here is another syntax, uses update() method to do the same task as of above:

my_dictionary.update({key: value})

Note - For key and/or value of string type, use double quote ("") to enclose key and/or value.

Important - While adding new item to the dictionary using any of the above two ways, will add a new item at the end of dictionary. And if the name of key already available in the dictionary, then the value of that key will get updated. It is because, dictionary does not allows duplicates.

Here is an example of adding/updating item to the dictionary based on user-inputs:

print("Enter 2 Items for the Dictionary.")
my_dictionary = {}
for i in range(2):
    print("Enter Key No.", i+1, ": ", end="", sep="")
    key = input()
    print("Enter Value for Key No.", i+1, ": ", end="", sep="")
    value = input()
    my_dictionary.update({key: value})

print("\nThe Dictionary is:")
print(my_dictionary)

Here is its sample run with user inputs, First Key and First Value as key and value for first item, whereas Second Key and Second Value as key and value for the second item of the dictionary:

adding key value pair python

Note - The end and sep are the two parameters of print(), used to change the default behavior of print statement.

Note - Since by default, the input() method treats every entered value as a string type. That is, whatever the value you enter, it gets converted into string automatically.

Now the example given below, shows how the value gets updated, if the key used to add new item already exists in the dictionary:

mydict = {"Name": "Jonah", "City": "Seattle"}
print(mydict)
mydict["City"] = "Bellingham"
print(mydict)

The output produced by above program will be:

{'Name': 'Jonah', 'City': 'Seattle'}
{'Name': 'Jonah', 'City': 'Bellingham'}

Find Length of a Dictionary in Python

To find length of a dictionary, use len() method as shown in the program given below:

my_dict = {1: "USA", 2: "UK", 3: "Australia"}
my_dict_len = len(my_dict)
print("The dictionary \"my_dict\" has", my_dict_len, "items.")

This will produce following output:

The dictionary "my_dict" has 3 items.

Delete an Item from a Dictionary in Python

To delete an item from a dictionary, use del keyword as shown in the example given below:

mydict = {"Day": "Wednesday", "Month": "October"}
print(mydict)

del mydict["Day"]
print(mydict)

The output produced by above Python program, will exactly be:

deleting key value pair python

As you can see from the above output, the second print of dictionary, the first item, whose key's name is Day is deleted.

The pop() method can also be used to pop/remove item from the dictionary using its key name as shown in the example given below:

mydict = {"Day": "Wednesday", "Month": "October"}
print(mydict)

mydict.pop("Day")
print(mydict)

The output will be same as of previous program.

Delete Last Item from a Dictionary

To delete last item from a dictionary, use popitem() as shown in the example given below:

mydict = {"Day": "Wednesday", "Month": "October"}
print(mydict)

mydict.popitem()
print(mydict)

mydict.popitem()
print(mydict)

The snapshot given below, shows the sample output produced by above Python program:

dictionary in python example

Note - Every time we use popitem(), the last item will get deleted from the dictionary.

Now the question is, what if the dictionary is/becomes empty and we use popitem() ?
Let's check it out using the program given below:

mydict = {"Name": "Jonah", "City": "Olympia"}
print(mydict)

mydict.popitem()
print(mydict)

mydict.popitem()
print(mydict)

mydict.popitem()
print(mydict)

The output, this time will be:

dictionary example python

See the error KeyError: 'popitem(): dictionary is empty' saying that the dictionary is empty, therefore no key is available to pop out. So we need to handle that KeyError error raised by using popitem() further when no item is available in the dictionary, like shown in the example given below:

mydict = {"Name": "Jonah", "City": "Yakima"}
print(mydict)

try:
    mydict.popitem()
    print(mydict)
except KeyError:
    print("\nThe Dictionary \"mydict\" is empty!")

try:
    mydict.popitem()
    print(mydict)
except KeyError:
    print("\nThe Dictionary \"mydict\" is empty!")

try:
    mydict.popitem()
    print(mydict)
except KeyError:
    print("\nThe Dictionary \"mydict\" is empty!")

Since to make program more dynamic, I assume that I don't know that at which popitem(), the dictionary is empty. Therefore, I've used try-except block to every popitem() to catch the error when raised. Here is the output produced by above program, this time:

python dictionary code

Since the same statement written three times, therefore it is a better practice to wrap all those statements, written multiple times with exactly same code, in a function. Here is the modified version of previous program:

def p(d):
    try:
        d.popitem()
        print(mydict)
    except KeyError:
        print("\nThe Dictionary \"mydict\" is empty!")

mydict = {"Name": "Jonah", "City": "Yakima"}
print(mydict)

p(mydict)
p(mydict)
p(mydict)

The output will exactly be same as of previous program.

Delete All Items of a Dictionary at Once

To delete all items from a dictionary at once, use clear() method as shown in the example given below:

mydict = {"Name": "Jonah", "City": "Everett"}
print(mydict)

mydict.clear()
print(mydict)

The output produced by above program will exactly be:

{'Name': 'Jonah', 'City': 'Everett'}
{}

See the output. That is, before using clear() method, we're seeing all the items of the dictionary. But after using clear() method, we're not seeing any items, because all the items are cleared.

Delete Whole Dictionary

The del keyword can also be used to delete the whole dictionary, as shown in the example given below.

mydict = {"Day": "Wednesday", "Month": "October"}
print(mydict)

del mydict
print(mydict)

Now the output produced by above program will produce the dictionary using first print(), and then produce error using second print(). Because, the dictionary is deleted using the del keyword before second print() statement. Let's see the output first, then will see how to handle the error:

python dictionary example

Since the name of raised error is NameError. Therefore, we need to handle this exception. Here is the demo program, shows how to handle these types of errors:

mydict = {"Day": "Wednesday", "Month": "October"}
print(mydict)

del mydict
try:
    print(mydict)
except NameError:
    print("\nThe dictionary \"mydict\" is empty!")

Now the output produced by above program, this time will be:

python dictionary

Since we already knows that the second print() raises an error while printing the dictionary mydict, therefore I've applied the try-except block to handle the error raised for the second print(). But you can put every where to check whether the dictionary we're going to print is empty or have some items.

Dictionary Comprehension in Python

We can also use iterables to create a dictionary in concise way, using small codes or single statements.

cubes = {n: n*n*n for n in range(1, 6)}
print(cubes)

In above program, before : (colon) refers to key, whereas after : refers to values. Since the range() method returns sequence of values. Therefore range(1, 6) returns 1, 2, 3, 4, 5. So the above program can also be written as:

cubes = {n: n*n*n for n in (1, 2, 3, 4, 5)}
print(cubes)

The output of this and previous program is same, that is:

{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

The value of n will be 1 at first time. Therefore, n: n*n*n or 1: 1*1*1 or 1: 1 will be initialized to cubes as its first item. Similarly n: n*n*n or 2: 2*2*2 or 2: 8 will get initialized to cubes as its second item, and so on.

The above and previous program can also be written as:

cubes = {}
for i in range(1, 6):
    cubes[i] = i*i*i
print(cubes)

Here is another example, prints squares or cubes of first 5 natural numbers based on user inputs:

print("1. Squares")
print("2. Cubes")
print("Enter Your Choice (1 or 2): ", end="")
try:
    ch_1 = int(input())
    if ch_1==1:
        print("\n1. Squares of First 5 Even Natural Numbers")
        print("2. Squares of First 5 Odd Natural Numbers")
        print("Enter Your Choice (1 or 2): ", end="")
        try:
            ch_2 = int(input())
            if ch_2==1:
                squares = {n: n*n for n in range(1, 11) if n%2==0}
                print("\n", squares, sep="")
            elif ch_2==2:
                squares = {n: n*n for n in range(1, 11) if n%2!=0}
                print("\n", squares, sep="")
        except ValueError:
            print("\nInvalid Input!")
    elif ch_1==2:
        print("\n1. Cubes of First 5 Even Natural Numbers")
        print("2. Cubes of First 5 Odd Natural Numbers")
        print("Enter Your Choice (1 or 2): ", end="")
        try:
            ch_2 = int(input())
            if ch_2==1:
                cubes = {n: n*n*n for n in range(1, 11) if n%2==0}
                print("\n", cubes, sep="")
            elif ch_2==2:
                cubes = {n: n*n*n for n in range(1, 11) if n%2!=0}
                print("\n", cubes, sep="")
        except ValueError:
            print("\nInvalid Input!")
except ValueError:
    print("\nInvalid Input!")

Here is its sample run with user input 1 and 2 as two choices:

python dictionary comprehension

This program is created to show you, how we can apply the condition while creating dictionary using dictionary comprehension.

Mega Program on Dictionary in Python

This the last and mega program on dictionary in Python. Concentrate on this program, to learn little extra things in Python:

mydict = {}
while True:
    print("\n1. Create Dictionary")
    print("2. Show Dictionary")
    print("3. Add Item to Dictionary")
    print("4. Update Dictionary")
    print("5. Delete Specific Item from Dictionary")
    print("6. Delete All Items from Dictionary")
    print("7. Exit")
    print("Enter Your Choice (1-7): ", end="")
    try:
        ch = int(input())
        if ch == 1:
            print("\nHow many items to store in dictionary ? ", end="")
            try:
                tot = int(input())
                print("Enter", tot, "Items for the dictionary.")
                for i in range(tot):
                    print("\nEnter key and value for item no.", i+1, ": ", end="", sep="")
                    key = input()
                    value = input()
                    mydict[key] = value
            except ValueError:
                print("\nInvalid Input!")
        elif ch == 2:
            print("\n----The Dictionary is----")
            for k, v in mydict.items():
                print(k, "->", v)
        elif ch == 3:
            print("\nHow many items to add ? ", end="")
            try:
                tot = int(input())
                print("Enter", tot, "Items for the dictionary.")
                for i in range(tot):
                    print("\nEnter key and value for item no.", i+1, ": ", end="", sep="")
                    key = input()
                    if key in mydict:
                        print("The key \"", key, "\" is already available!", sep="")
                    else:
                        value = input()
                        mydict[key] = value
            except ValueError:
                print("\nInvalid Input!")
        elif ch == 4:
            print("\nHow many item to update ? ", end="")
            try:
                tot = int(input())
                if tot > len(mydict):
                    print("\nThere is only", len(mydict), "items in the dictionary!")
                else:
                    for i in range(tot):
                        print("Which key to update ? ", end="")
                        key = input()
                        if key in mydict:
                            print("Enter new value for this key: ", end="")
                            value = input()
                            mydict[key] = value
                        else:
                            print("\nThe entered key is not found!")
            except ValueError:
                print("\nInvalid Input!")
        elif ch == 5:
            print("\nHow many item to delete ? ", end="")
            try:
                tot = int(input())
                if tot > len(mydict):
                    print("\nThere is only", len(mydict), "items in the dictionary!")
                else:
                    for i in range(tot):
                        print("Which key to delete ? ", end="")
                        key = input()
                        if key in mydict:
                            del mydict[key]
                        else:
                            print("\nThe entered key is not found!")
            except ValueError:
                print("\nInvalid Input!")
        elif ch == 6:
            print("\nAre you sure to delete all items ? (y/n): ", end="")
            c = input()
            if c=='y':
                mydict.clear()
                print("The dictionary is now empty!")
        elif ch == 7:
            break
        else:
            print("\nInvalid Choice!")
    except ValueError:
        print("\nInvalid Choice!")

Here is its sample run with user input 1 as choice, and 2 as number of item to insert or add, then First Key and First Value as first item, whereas Second Key and Second Value as second item to add:

python dictionary mega program

Since the whole program is wrapped into a while loop, whose condition is provided as True that always evaluates to be True, until a break keyword occurs, that happens when you enter 7 as choice to exit from the program. Therefore after displaying the output, the program still continues its execution. So let's take another choice. This time, I'm going with 4 as choice to update, then 1 as number of item to update, First Key as key, and Value of First Key as its new value:

python dictionary example program

The program is created in a way to handle all the errors when user enters any invalid input. You can check it out with yourself. It will enhance your skill when you'll cross-check the program.

Python Online Test


« Previous Tutorial Next Tutorial »



© Copyright 2021. All Rights Reserved.

CodesCracker