Python Dictionary with Methods, Functions and Dictionary Operations

Free Python courses with 57 real-time projects - Learn Python

In the last few lessons, we have learned about some Python constructs like lists and tuples. Today, we will have a word about Python dictionary which is another type of data structure in Python.

Moreover, we will study how to create, access, delete, reassign dictionary in Python. Along with this, we will learn Python Dictionary method and operations.

So, let’s start the Python Dictionary Tutorial.

Python Dictionary

Python Dictionary

What are Python Dictionaries?

A real-life dictionary holds words and their meanings. As you can imagine, likewise, a Python dictionary holds key-value pairs.

Let’s look at how to create one.

How to Create a Dictionary in Python?

Creating a Python Dictionary is easy as pie. Separate keys from values with a colon(:), and a pair from another by a comma(,). Finally, put it all in curly braces.

>>> {'PB&J':'Peanut Butter and Jelly','PJ':'Pajamas'}

Output

{‘PB&J’: ‘Peanut Butter and Jelly’, ‘PJ’: ‘Pajamas’}

Optionally, you can put the dictionary in a variable. If you want to use it later in the program, you must do this.

>>> lingo={'PB&J':'Peanut Butter and Jelly','PJ':'Pajamas'}

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

To create an empty dictionary, simply use curly braces and then assign it to a variable

>>> dict2={}
>>> dict2

Output

{}
>>> type(dict2)

Output

<class ‘dict’>

1. Python Dictionary Comprehension

You can also create a Python dict using comprehension. This is the same thing that you’ve learned in your math class.

To do this, follow an expression pair with a for-statement loop in python. Finally, put it all in curly braces.

>>> mydict={x*x:x for x in range(8)}
>>> mydict

Output

{0: 0, 1: 1, 4: 2, 9: 3, 16: 4, 25: 5, 36: 6, 49: 7}

In the above code, we created a Python dictionary to hold squares of numbers from 0 to 7 as keys, and numbers 0-1 as values.

2. Dictionaries with mixed keys

It isn’t necessary to use the same kind of keys (or values) for a dictionary in Python.

>>> dict3={1:'carrots','two':[1,2,3]}
>>> dict3

Output

{1: ‘carrots’, ‘two’: [1, 2, 3]}

As you can see here, a key or a value can be anything from an integer to a list.

3. dict()

Using the dict() function, you can convert a compatible combination of constructs into a Python dictionary.

>>> dict(([1,2],[2,4],[3,6]))

Output

{1: 2, 2: 4, 3: 6}

However, this function takes only one argument. So if you pass it three lists, you must pass them inside a list or a tuple. Otherwise, it throws an error.

>>> dict([1,2],[2,4],[3,6])

Output

Traceback (most recent call last):File “<pyshell#121>”, line 1, in <module>

dict([1,2],[2,4],[3,6])

TypeError: dict expected at most 1 arguments, got 3

4. Declaring one key more than once

Now, let’s try declaring one key more than once and see what happens.

>>> mydict2={1:2,1:3,1:4,2:4}
>>> mydict2

Output

{1: 4, 2: 4}

As you can see, 1:2 was replaced by 1:3, which was then replaced by 1:4. This shows us that a dictionary cannot contain the same key twice.

5. Declaring an empty dictionary and adding elements later

When you don’t know what key-value pairs go in your Python dictionary,  you can just create an empty Python dict, and add pairs later.

>>> animals={}
>>> type(animals)

Output

<class ‘dict’>
>>> animals[1]='dog'
>>> animals[2]='cat'
>>> animals[3]='ferret'
>>> animals

Output

{1: ‘dog’, 2: ‘cat’, 3: ‘ferret’}

Any query on Python Dictionay yet? Leave a comment.

How to Access a Python Dictionary?

1. Accessing the entire Python dictionary

To get the entire dictionary at once, type its name in the shell.

>>> dict3

Output

{1: ‘carrots’, ‘two’: [1, 2, 3]}

2. Accessing a value

To access an item from a list or a tuple, we use its index in square brackets. This is the python syntax to be followed. However, a Python dictionary is unordered. So to get a value from it, you need to put its key in square brackets.

To get the square root of 36 from the above dictionary, we write the following code.

>>> mydict[36]

Output

6

3. get()

The Python dictionary get() function takes a key as an argument and returns the corresponding value.

>>> mydict.get(49)

Output

7

4. When the Python dictionary keys doesn’t exist

If the key you’re searching for doesn’t exist, let’s see what happens.

>>> mydict[48]

Output

Traceback (most recent call last):File “<pyshell#125>”, line 1, in <module>

mydict[48]

KeyError: 48

Using the key in square brackets gives us a KeyError. Now let’s see what the get() method returns in such a situation.

>>> mydict.get(48)
>>>

As you can see, this didn’t print anything. Let’s put it in the print statement to find out what’s going on.

>>> print(mydict.get(48))

Output

None

So we see, when the key doesn’t exist, the get() function returns the value None. We discussed it earlier, and know that it indicates an absence of value.

Reassigning a Python Dictionary

The python dictionary is mutable. This means that we can change it or add new items without having to reassign all of it.

1. Updating the Value of an Existing Key

If the key already exists in the Python dictionary, you can reassign its value using square brackets.

Let’s take a new Python dictionary for this.

>>> dict4={1:1,2:2,3:3}

Now, let’s try updating the value for the key 2.

>>> dict4[2]=4
>>> dict4

Output

{1: 1, 2: 4, 3: 3}

2. Adding a new key

However, if the key doesn’t already exist in the dictionary, then it adds a new one.

>>> dict4[4]=6
>>> dict4

Output

{1: 1, 2: 4, 3: 3, 4: 6}

Python dictionary cannot be sliced.

How to Delete Python Dictionary?

You can delete an entire dictionary. Also, unlike a tuple, a Python dictionary is mutable. So you can also delete a part of it.

1. Deleting an entire Python dictionary

To delete the whole Python dict, simply use its name after the keyword ‘del’.

>>> del dict4
>>> dict4

Output

Traceback (most recent call last):File “<pyshell#138>”, line 1, in <module>

dict4

NameError: name ‘dict4’ is not defined

2. Deleting a single key-value pair

To delete just one key-value pair, use the keyword ‘del’ with the key of the pair to delete.

Now let’s first reassign dict4 for this example.

>>> dict4={1:1,2:2,3:3,4:4}

Now, let’s delete the pair 2:2

>>> del dict4[2]
>>> dict4

Output

{1: 1, 3: 3, 4: 4}

A few other methods allow us to delete an item from a dictionary in Python. We will see those in section 8.

In-Built Functions on a Python Dictionary

A function is a procedure that can be applied on a construct to get a value. Furthermore, it doesn’t modify the construct. Python gives us a few functions that we can apply on a Python dictionary. Take a look.

1. len()

The len() function returns the length of the dictionary in Python. Every key-value pair adds 1 to the length.

>>> len(dict4)

Output

3

An empty Python dictionary has a length of 0.

>>> len({})

2. any()

Like it is with lists an tuples, the any() function returns True if even one key in a dictionary has a Boolean value of True.

>>> any({False:False,'':''})

Output

False
>>> any({True:False,"":""})

Output

True
>>> any({'1':'','':''})

Output

True

3. all()

Unlike the any() function, all() returns True only if all the keys in the dictionary have a Boolean value of True.

>>> all({1:2,2:'',"":3})

Output

False

4. sorted()

Like it is with lists and tuples, the sorted() function returns a sorted sequence of the keys in the dictionary. The sorting is in ascending order, and doesn’t modify the original Python dictionary.

But to see its effect, let’s first modify dict4.

>>> dict4={3:3,1:1,4:4}

Now, let’s apply the sorted() function on it.

>>> sorted(dict4)

Output

[1, 3, 4]

Now, let’s try printing the dictionary dict4 again.

>>> dict4

Output

{3: 3, 1: 1, 4: 4}

As you can see, the original Python dictionary wasn’t modified.

This function returns the keys in a sorted list. To prove this, let’s see what the type() function returns.

>>> type(sorted(dict4))

Output

<class ‘list’>

This proves that sorted() returns a list.

In-Built Methods on a Python Dictionary

A method is a set of instructions to execute on a construct, and it may modify the construct. To do this, a method must be called on the construct. Now, let’s look at the available methods for dictionaries.

Let’s use dict4 for this example.

>>> dict4

Output

{3: 3, 1: 1, 4: 4}

1. keys()

The keys() method returns a list of keys in a Python dictionary.

>>> dict4.keys()

Output

dict_keys([3, 1, 4])

2. values()

Likewise, the values() method returns a list of values in the dictionary.

>>> dict4.values()

Output

dict_values([3, 1, 4])

3. items()

This method returns a list of key-value pairs.

>>> dict4.items()

Output

dict_items([(3, 3), (1, 1), (4, 4)])

4. get()

We first saw this function in section 4c. Now, let’s dig a bit deeper.

It takes one to two arguments. While the first is the key to search for, the second is the value to return if the key isn’t found.

The default value for this second argument is None.

>>> dict4.get(3,0)

Output

3
>>> dict4.get(5,0)

Since the key 5 wasn’t in the dictionary, it returned 0, like we specified.

Any doubt yet in Python Dictionary? Leave a comment.

5. clear()

The clear function’s purpose is obvious. It empties the Python dictionary.

>>> dict4.clear()
>>> dict4

Output

{}

Let’s reassign it though for further examples.

>>> dict4={3:3,1:1,4:4}

6. copy()

First, let’s see what shallow and deep copies are. A shallow copy only copies contents, and the new construct points to the same memory location.

But a deep copy copies contents, and the new construct points to a different location. The copy() method creates a shallow copy of the Python dictionary.

>>> newdict=dict4.copy()
>>> newdict

Output

{3: 3, 1: 1, 4: 4}

7. pop()

This method is used to remove and display an item from the dictionary. It takes one to two arguments. The first is the key to be deleted, while the second is the value that’s returned if the key isn’t found.

>>> newdict.pop(4)

Output

4

Now, let’s try deleting the pair 4:4.

>>> newdict.pop(5,-1)

Output

-1

However, unlike the get() method, this has no default None value for the second parameter.

>>> newdict.pop(5)

Output

Traceback (most recent call last):File “<pyshell#191>”, line 1, in <module>

newdict.pop(5)

KeyError: 5

As you can see, it raised a KeyError when it couldn’t find the key.

8. popitem()

Let’s first reassign the Python dictionary newdict.

>>> newdict={3:3,1:1,4:4,7:7,9:9}

Now, we’ll try calling popitem() on this.

>>> newdict.popitem()

Output

(9, 9)

It popped the pair 9:9.

Let’s restart the shell and reassign the dictionary again and see which pair is popped.

=============================== RESTART: Shell ===============================
>>> newdict={3:3,1:1,4:4,7:7,9:9}
>>> newdict.popitem()

Output

(9, 9)

As you can see, the same pair was popped. We can interpret from this that the internal logic of the popitem() method is such that for a particular dictionary, it always pops pairs in the same order.

9. fromkeys()

This method creates a new Python dictionary from an existing one. To take an example, we try to create a new dictionary from newdict.

While the first argument takes a set of keys from the dictionary, the second takes a value to assign to all those keys. But the second argument is optional.

>>> newdict.fromkeys({1,2,3,4,7},0)

Output

{1: 0, 2: 0, 3: 0, 4: 0, 7: 0}

However, the keys don’t have to be in a set.

>>> newdict.fromkeys((1,2,3,4,7),0)

Output

{1: 0, 2: 0, 3: 0, 4: 0, 7: 0}

Like we’ve seen so far, the default value for the second argument is None.

>>> newdict.fromkeys({'1','2','3','4','7'})

Output

{‘4’: None, ‘7’: None, ‘3’: None, ‘1’: None, ‘2’: None}

10. update()

The update() method takes another dictionary as an argument. Then it updates the dictionary to hold values from the other dictionary that it doesn’t already.

>>> dict1={1:1,2:2}
>>> dict2={2:2,3:3}
>>> dict1.update(dict2)
>>> dict1

Output

{1: 1, 2: 2, 3: 3}

Python Dictionary Operations

We learned about different classes of operators in Python earlier. Let’s now see which of those can we apply on dictionaries.

1. Membership

We can apply the ‘in’ and ‘not in’ operators on a Python dictionary to check whether it contains a certain key.

For this example, we’ll work on dict1.

>>> dict1

Output

{1: 1, 2: 2, 3: 3}
>>> 2 in dict1

Output

True
>>> 4 in dict1

Output

False

2 is a key in dict1, but 4 isn’t. Hence, it returns True and False for them, correspondingly.

Python Iterate Dictionary

When in a for loop, you can also iterate on a Python dictionary like on a list, tuple, or set.

>>> dict4

Output

{1: 1, 3: 3, 4: 4}
>>> for i in dict4:
	print(dict4[i]*2)

Output

2
6
8

The above code, for every key in the Python dictionary, multiplies its value by 2, and then prints it.

Nested Dictionary

Finally, let’s look at nested dictionaries. You can also place a Python dictionary as a value within a dictionary.

>>> dict1={4:{1:2,2:4},8:16}
>>> dict1

Output

{4: {1: 2, 2: 4}, 8: 16}

To get the value for the key 4, write the following code.

>>> dict1[4]

Output

{1: 2, 2: 4}

However, you can’t place it as a key, because that throws an error.

>>> dict1={{1:2,2:4}:8,8:16}

Output

Traceback (most recent call last):File “<pyshell#227>”, line 1, in <module>

dict1={{1:2,2:4}:8,8:16}

TypeError: unhashable type: ‘dict’

So, this was all about Python Dictionary tutorial. Hope you like our explanation

Python Interview Questions on Dictionaries

  1. What are Python dictionaries?
  2. How do you call a dictionary in Python?
  3. Explain Dictionaries working in Python?
  4. How do you read a dictionary in Python?
  5. How do you create an empty dictionary?

Conclusion

In today’s lesson, we took a deep look at Python Dictionary. We first saw how to create, access, reassign, and delete a dictionary or its elements.

Then we looked at built-in functions and methods for dictionaries. After that, we learned about the operations that we can perform on them.

Lastly, we learned about nested dictionaries and how to iterate on a Python dictionary. Still, you have a confusion? feel free to ask in the comment box.

Your opinion matters
Please write your valuable feedback about DataFlair on Google

follow dataflair on YouTube

3 Responses

  1. Ashana says:

    the update function mentioned, doesn’t support in Python 3.8. It throws error.
    Error- “d2.update[7]=9 TypeError: ‘builtin_function_or_method’ object does not support item assignment”
    neither does “d2.update[6:9]” is supported

    Error- “d2.update[6:9]
    TypeError: ‘builtin_function_or_method’ object is not subscriptable”
    Please check and update on the site for future help

    • DataFlair says:

      The update() method takes another dictionary as an argument and you are are passing a dictionary which is why you are getting this error.

  2. Julaha Zainab says:

    Use shell 3.7

Leave a Reply

Your email address will not be published. Required fields are marked *