Understanding The Dictionary in Python

Dictionary-python
Dictionary-python

Introduction

Do you know the meaning of the word “Serendipity”? 

If not, you’d probably just looked up the meaning, and you just made a happy and unexpected addition to your vocabulary. 

Now, think back to the times when we couldn’t just Google search the meaning of words. What did we use then?


Source: giphy

A dictionary, of course!

Now, how did we use the dictionary? 

We looked up a word, and its meaning would be given alongside.

A dictionary in Python is a similar tool. It stores a key, and a value is associated with each key. 

Now while using a dictionary, do we search the meaning of the word or the word itself? 

The answer to this question is obvious, and we know that we search for a word. 

Similarly, in a dictionary in Python, to access the values, we use its keys.

To get a clear picture of keys and values, let us see a diagram:



The picture above shows that certain words are our keys and their meanings are the values. 

With this, we can draw a similarity between a dictionary in Python and the traditional dictionaries used by us. 

Thus, to formally define a dictionary in Python,

A dictionary in Python is used to store data in the form of key-value pairs. 

Python dictionary

Dictionaries are one of the fundamental data structures in Python. A dictionary can hold an arbitrary number of objects, each of which is identified by a distinct dictionary key. 

Some of the points regarding dictionaries are given below.

  • Keys are case sensitive, i.e. “NAME” and “name” are two different keys.
  • Maps, hashmaps, lookup tables, and associative arrays are other names for dictionaries. 

Ordered:

It implies that the items are placed in a specific sequence that will not change. Dictionary follows the insertion order.

Note: Python 3.6 introduced the order-preserving aspect of the dictionary, which is also applicable to subsequent versions. Earlier dictionaries were unordered collections; you can refer to the official documentation for detailed information.

Mutable:

Dictionaries are mutable, which means that after they’ve been created, we can modify, add, or remove items.

No Duplicates:

Since items are accessed using their key. There can’t be two items with the same key in a dictionary.

Creating Dictionary

There are two basic ways to create a dictionary in python.

  1. Using curly braces.
  2. Using dict()constructor.

Method-1

  1. An empty dictionary is created by a pair of braces {}.

Example D1 = {} 

D1 = {}
print(D1)
Output
{}
  1. A simple dictionary can be created by placing items inside curly braces {} separated by commas.
Example D2 = {"Name": "Elon Musk", "Age": 42}  
D2 = {“Name”: “Elon Musk”, “Age”: 42}
print(D2)

Output
{‘Name’: ‘Elon Musk’, ‘Age’: 42 }

Method-2

  1. The in-built dict()constructor can also be used to create a dictionary.

Example D3 = dict(India=91, China=86, Bhutan=975)

D3 = dict(India=91, China=86, Bhutan=975)
print(D3)

Output
{‘India’: 91, ‘China’: 86, ‘Bhutan’: 975}
  1. The dict() constructor also builds dictionaries directly from sequences of key-value pairs.

Example – D4= dict([(‘India’, 91), (‘China’, 86), (‘Bhutan’, 975)])

D4 = dict([(‘India’, 91), (‘China’, 86), (‘Bhutan’, 975)])
print(D4)

Output
{‘India’: 91, ‘China’: 86, ‘Bhutan’: 975}

Now that we know what a dictionary in Python is and how it is created, let us see what can be stored in them.

Data stored in the dictionary

You may be wondering what kind of data can be used as a key or a value in the dictionary.

The keys in a dictionary in Python have two limitations:

  1. They cannot be duplicate values. If two keys are the same but have different values, the second key will override the first one. 

For example,

random = {1:”one”, 2:”two”, 3:”three”, 1:”pizza”}
print(random)

Output:

{1: ‘pizza’, 2: ‘two’, 3: ‘three’}
  1. Keys must be of an immutable type.

For example, integer, float, string, boolean and tuple. So, lists and dictionaries cannot be keys since they’re mutable. 

myTuple = (“Hello”, “Hi”)
myDictionary = {“Fruit”:”Apple”}
random = {1:”one”, 2.0:”two”, True:”three”, “Four”:4, myTuple:”five”, myDictionary:”six”}
print(random)

Output:

TypeError                                 Traceback (most recent call last)

<ipython-input-3-571442cf7c68> in <module>()
      2 myDictionary = {“Fruit”:”Apple”}
      3 myList = [0,1,2]
—-> 4 random = {1:”one”, 2.0:”two”, True:”three”, “Four”:4, myTuple:”five”, myDictionary:”six”, myList:”seven”}
      5 print(random)


TypeError: unhashable type: ‘dict’
myTuple = (“Hello”, “Hi”)
myDictionary = {“Fruit”:”Apple”}
random = {1:”one”, 2.0:”two”, True:”three”, “Four”:4, myTuple:”five”}
print(random)

Output:

{1: ‘three’, 2.0: ‘two’, ‘Four’: 4, (‘Hello’,’Hi’) : ‘five’}

Curious to know about the different data types in Python? Check out this blog here.

On the other hand, in Python dictionary values can be of any type and may even be repeated. 

With this, we come to an important idea of Nested dictionaries. Let us see what that is next.

Nested Dictionary in Python

By definition, nested means one inside the other. So, a Nested dictionary means a dictionary inside another dictionary. 

We already know that a dictionary cannot be a key since it is mutable. Still, a dictionary can always be the value in a dictionary in Python. 

Such a dictionary in which a value is another dictionary is known as a Nested dictionary in Python. 

For example, 

ones = {1:”one”, 2:”two”, 3:”three”, 4:”four”, 5:”five”, 6:”six”, 7:”seven”, 8:”eight”, 9:”nine”}
tens = {10:”ten”, 20:”twenty”, 30:”thirty”, 40:”forty”, 50:”fifty”, 60:”sixty”, 70:”seventy”, 80:”eighty”, 90:”ninety”}
numbers = {1:tens, 2:ones}
print(numbers)

Output:

{1: {10: ‘ten’, 20: ‘twenty’, 30: ‘thirty’, 40: ‘forty’, 50: ‘fifty’, 60: ‘sixty’, 70: ‘seventy’, 80: ‘eighty’, 90: ‘ninety’}, 2: {1: ‘one’, 2: ‘two’, 3: ‘three’, 4: ‘four’, 5: ‘five’, 6: ‘six’, 7: ‘seven’, 8: ‘eight’, 9: ‘nine’}}

Adding, Removing, and Accessing Elements in a Dictionary

The next basic operation we need to know about a dictionary is adding, removing and accessing elements. So let’s see how those are done.

Adding an Element

To add a key-value pair to a dictionary, Python provides an in-built function called update. The syntax to use it is:

dictionary_name.update({key:value})

To understand this better, let us see an example.

random = {1:”one”, 2:”two”, 3:”three”}
print(random)
random.update({4:”four”})
print(“AFTER UPDATING:”)
print(random)

Output:

{1: ‘one’, 2: ‘two’, 3: ‘three’}
AFTER UPDATING:
{1: ‘one’, 2: ‘two’, 3: ‘three’, 4: ‘four’}

Removing an Element

Like the update( ) method, Python also has an in-built to delete either the entire dictionary or a key-value pair. Its syntax is as follows:

del(dictionary_name)

OR

del(dictionary_name[key])

Let us see an example of each of these operations.

Deleting the entire dictionary

random = {1:”one”, 2:”two”, 3:”three”}
print(random)
del(random)
print(“AFTER DELETING:”)
print(random)

Output:

{1: ‘one’, 2: ‘two’, 3: ‘three’}
AFTER DELETING:

——————————————————————

NameError                        Traceback (most recent call last)

<ipython-input-4-f38e1d672962> in <module>()
      3 del(random)
      4 print(“AFTER DELETING:”)
—-> 5 print(random)


NameError: name ‘random’ is not defined

Deleting a key-value pair

random = {1:”one”, 2:”two”, 3:”three”}
print(random)
del(random[1])
print(“AFTER DELETING:”)
print(random)

Output:

{1: ‘one’, 2: ‘two’, 3: ‘three’}
AFTER DELETING:
{2: ‘two’, 3: ‘three’}

Accessing an Element

The easiest way to access an element in a dictionary is by using its key. This can be done using the following syntax:

dictionary_name[key]

For example,

random = {1:”one”, 2:”two”, 3:”three”}
print(random[2])

Output:

two

We can also access the keys, values and the key-value pairs by in-built Python functions keys( ), values( ) and items( ), respectively. They are used as shown below:

random = {1:”one”, 2:”two”, 3:”three”}
print(random.keys())
print(random.values())
print(random.items())

Output:

dict_keys([1, 2, 3])
dict_values([‘one’, ‘two’, ‘three’])
dict_items([(1, ‘one’), (2, ‘two’), (3, ‘three’)])

Now, previously we discussed nested dictionaries, so we must know how to access their elements too. The syntax for it is as shown below:

dictionary_name1[key_in_dictionary1][key_in_dictionary2]

Considering our previous example,

ones = {1:”one”, 2:”two”, 3:”three”, 4:”four”, 5:”five”, 6:”six”, 7:”seven”, 8:”eight”, 9:”nine”}

tens = {10:”ten”, 20:”twenty”, 30:”thirty”, 40:”forty”, 50:”fifty”, 60:”sixty”, 70:”seventy”, 80:”eighty”, 90:”ninety”}

numbers = {1:tens, 2:ones}print(numbers[1][10])

Output:

ten

There are alternate methods for all three operations discussed above. 

Curious to learn more about them? Don’t worry because you can easily find them all here.

Practical Use of a Dictionary

Now that we know how to use dictionaries, let us solve one question. 

Suppose we have a string and we want to find the frequency of each letter used in it. To do this, we will use a dictionary and map the frequency of each letter. 

Are you curious as to how? It’s simple store each letter in the dictionary as a key and its occurrence as a value.

The code is straightforward, and I am pretty sure you can figure it out yourself too, but for your help, the solution is given below:

str = “abcdbbcdaacdbbcadacbc”
freq = dict()
ct = 0
for each in str:
  if each in freq.keys():
    freq[each]+=1
  else:
    freq[each] = 1
for key,value in freq.items():
  print(key,value)

Output:

a 5
b 6
c 6
d 4

Don’t stop there; use CodeStudio to try out a variation of the preceding problem, Maximum Frequency Number, and get it accepted straight away.

Frequently Asked Questions

What is an example of a dictionary in Python?

An example of a dictionary in Python would be as follows:
digits = {1:”one”, 2:”two”, 3:”three”, 4:”four”, 5:”five”, 6:”six”, 7:”seven”, 8:”eight”, 9:”nine”}

What are dictionaries used for in Python? 

Dictionaries in Python are used to store key-value pairs in a mutable data structure.

How do you create a dictionary in Python? 

A dictionary in Python can be created in two ways as follows:
Using curly braces ( { } ):
myDictionary = {“name”:”Neelakshi”, “age”:21 }
Using the dict( ) constructor:
myDictionary = dict(name=”Neelakshi”, age=21)

Is Python dictionary a hashmap?

In Python, dictionaries are a counterpart of hashmaps in Java.  

Are Dictionaries mutable in Python?

Yes, dictionaries in Python are mutable.

Key Takeaways

By now, we have learned about dictionaries and some basic operations on them. But that’s not all there is to dictionaries. 

There are many methods in Python specifically for dictionaries. To learn about them, you can go through this blog.

Apart from this, you can also practice the vast array of coding questions asked in the interviews of renowned companies. They are collectively available at CodeStudio

Exit mobile version