Dictionary in Python

Dictionary in Python with Examples

In this article, I am going to discuss Dictionary in Python with Examples. Please read our previous article where we discussed Sets in Python with examples. As part of this article, we are going to discuss the following pointers which are related to Dictionary in Python.

  1. What is a dictionary in python?
  2. How to Create a dictionary in python?
  3. Access values by using keys from the dictionary
  4. Handling errors
  5. Important functions and methods of dictionary
  6. Dictionary Comprehension
  7. Multiple Programs to understand the above concepts.
Dictionaries in Python:

In python, to represent a group of individual objects as a single entity then we have used lists, tuples, sets. If we want to represent a group of objects as key-value pairs then we should go for dictionaries.

Characteristics of Dictionary
  1. Dictionary will contain data in the form of key, value pairs.
  2. Key and values are separated by a colon “:” symbol
  3. One key-value pair can be represented as an item.
  4. Duplicate keys are not allowed.
  5. Duplicate values can be allowed.
  6. Heterogeneous objects are allowed for both keys and values.
  7. Insertion order is not preserved.
  8. Dictionary object having mutable nature.
  9. Dictionary objects are dynamic.
  10. Indexing and slicing concepts are not applicable
How to Create a dictionary in Python?

The syntax for creating dictionaries with key,value pairs is: d = {key1:value1, key2:value2, …., keyN:valueN}

Example: creating dictionary (demo1.py)
d ={1:"Ramesh", 2:"Arjun", 3:"Nireekshan"}
print(d)

Output: How to Create dictionary in Python?

Creating an Empty dictionary in Python:

We can create empty dictionaries by using curly braces. And later on, we can add the key-value pairs into it as shown in the below example.

Example: creating an empty dictionary and adding the items (demo2.py)
d = {}
d[1] = "Ramesh"
d[2] = "Suresh"
d[3] = "Mahesh"
print(d)

Output: Creating an Empty dictionary in Python

ACCESSING DICTIONARIES IN PYTHON:

We can access dictionary values by using keys. Keys play a main role to access the data.

Example: Accessing dictionary values by using keys (demo3.py)
d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}
print(d[1])
print(d[2])
print(d[3])
Output:

Accessing dictionary values by using keys

While accessing, if the specified key is not available then we will get KeyError

Example: KeyError (demo4.py)
d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}
print(d[10])

Output: KeyError

How to handle this KeyError?

We can handle this error by checking whether a key is already available or not by using “in” operator. There is also another precise way of handling this error, which we shall discuss later.

Example: Handle KeyError in Python Dictionary(demo5.py)
d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}
if 400 in d:
   print(d[400])
else:
   print("key not found")

Output: Handle KeyError in Python Dictionary

Example: Employee info program by using a dictionary(demo6.py)
d={}
n=int(input("Enter number of employees: "))
i=1
while i <=n:
   name=input("Enter Employee Name: ")
   salary=input("Enter Employee salary: ")
   d[name]=salary
   i=i+1

for x in d:
   print("The name is: ", x ," and his salary is: ", d[x])
Output

Employee info program by using dictionary

Updating a dictionary in Python:

We can update the value for a particular key in a dictionary. The syntax is:

d[key] = value

Case1: While updating the key in the dictionary, if the key is not available then a new key will be added at the end of the dictionary with the specified value

Case2: If the key is already existing in the dictionary, then the old value will be replaced with a new value

Example: Updating a dictionary – Case 1(demo7.py)
d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}
print("Old dictionary:", d)
d[10]="Hari"
print("Added key-value(10:Hari) pair to dictionary:",d)
Output

Updating a dictionary in Python

Example: Updating a dictionary – Case 2(demo8.py)
d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}
print("Old dictionary:", d)
d[3]="Hari"
print("UPdated value of key 3 pair to dictionary:",d)
Output

Updating a dictionary in Python

Removing or deleting elements from the dictionary in Python:
  1. By using the del keyword, we can remove the keys
  2. By using clear() we can clear the objects in the dictionary
By using the del keyword

Syntax: del d[key]

As per the syntax, it deletes entries associated with the specified key. If the key is not available, then we will get KeyError

Example: By using del keyword (demo9.py)
d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}
print("Before deleting key from dictionary",d)
del d[1]
print("After deleting key from dictionary:", d)
Output

Removing or deleting elements from dictionary in Python using del keyword

Example: By using del() (demo10.py)

d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}
print("Before deleting key from dictionary",d)
del d[10]
print("After deleting key from dictionary:", d)

Output: Removing or deleting elements from dictionary in Python using del() method

By Using clear() method:

The clear () method removes all entries in the dictionary. After deleting all entries, it just keeps an empty dictionary.

Example: By using clear() (demo11.py)
d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}
print("Before clearing dictionary: ", d)
d.clear()
print("After cleared entries in dictionary: ", d)
Output:

Removing or deleting elements from dictionary in Python using Clear() method

Delete total dictionary object in Python:

We can also use the del keyword to delete the total dictionary object. Before deleting we just have to note that once it is deleted then we cannot access the dictionary.

Syntax: del nameofthedictonary

Example: Deleting the dictionary (demo12.py)
d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}
print("Before clearing dictionary: ", d)
del d
print("After cleared entries in dictionary: ", d)
Output

Delete total dictionary object in Python

Functions and methods of dictionary in Python
  1. dict() function
  2. dict({key1:value1, key2:value2}) function
  3. dict([tuple1,tuple2])
  4. len() function
  5. clear() method
  6. get() method
  7. pop() method
  8. popitem() method
  9. keys() method
  10. Items() method
  11. keys() method
  12. copy() method
dict() function:

This can be used to create an empty dictionary. Later, we can add elements to that created dictionary

Example:
d=dict()
print(d)
print(type(d))
Output

dict() function

dict({key1:value1, key2:value2}) function:

It creates dictionary with specified elements

Example:
d = dict({1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'})
print(d)

Output: dict({key1:value1, key2:value2}) function

dict([tuple1,tuple2]):

This function creates a dictionary with the given list of tuple elements

Example:
d = dict([(1, "Ramesh"), (2, "Arjun")])
print(d)

Output: dict([tuple1,tuple2])

len() function:

This function returns the number of items in the dictionary

Example:
d = dict([(1, "Ramesh"), (2, "Arjun")])
print("length of dictionary is: ",len(d))

Output: len() function

clear() method:

This method can remove all elements from the dictionary. We have already discussed this above.

get() method:

This method used to get the value associated with the key. This is another way to get the values of the dictionary based on the key. The biggest advantage it gives over the normal way of accessing a dictionary is, this doesn’t give any error if the key is not present. Let’s see through some examples:

Case1: If the key is available, then it returns the corresponding value otherwise returns None. It won’t raise any errors. Syntax: d.get(key)

Case 2: If the key is available, then returns the corresponding value otherwise returns the default value that we give. Syntax: d.get(key, defaultvalue)

Example:
d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}
print(d.get(1))

print(d.get(100))
Output

get() method

Example:
d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}
print(d.get(1))

print(d.get(100,'No key found'))
Output

get() method

pop() method:

This method removes the entry associated with the specified key and returns the corresponding value. If the specified key is not available, then we will get KeyError

Syntax: d.pop(key)

Example:
d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}
print("Before pop:", d)
d.pop(1)
print("After pop:", d)
Output

pop() method

Example:
d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}
d.pop(23)

Output: pop() method

popitem() method:

This method removes an arbitrary item(key-value) from the dictionary and returns it.

Example:
d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}
print("Before popitem:", d)
d.popitem()
print("After popitem:", d)
Output

popitem() method

If the dictionary is empty, then we will get KeyError

Example:
d= {}
d.popitem()
print("After popitem:", d)

Output: popitem() method

keys() method:

This method returns all keys associated with the dictionary.

Example:
d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}
print(d)
for k in d.keys():
   print(k)
Output

keys() method

values() method:

This method returns all values associated with the dictionary

Example:
d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}
print(d)
for k in d.values():
   print(k)
Output

values() method

items() method:

A key-value pair in a dictionary is called an item. items() method returns the list of tuples representing key-value pairs.

Example:
d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}
for k, v in d.items():
   print(k, "---", v)
Output

items() method

copy() method:

To create an exactly duplicate dictionary (cloned copy)

Example:
d1 = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}
d2=d1.copy()
print(d1)
print(d2)
Output:

copy() method

Dictionary Comprehension in Python:

Just as we had lists and sets comprehensions, we also have this concept applicable for dictionaries even.

Example:
squares={a:a*a for a in range(1,6)}
print(squares)

Output: Dictionary Comprehension in Python

In the next article, I am going to discuss OOPs in Python. Here, in this article, I try to explain Dictionary in Python with Examples. I hope you enjoy this Dictionary in Python with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

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