Dictionary Datatype

The dictionary datatype is unlike other datatypes in python, dictionary datatype is used to store key-value pairs to make it more optimized.

The syntax for the dictionary data type is:

dictionary={k1:v1,k2:v2,k3:v3} 
##where k1 =first key , k2=second key, k3=Third key
 ## and v1=first value,v2=second value, v3=Third value

The properties of Dictionary Datatype

  • To represent a group of key values then we will use Dictionary data type
  • Here we can use duplicate values but we cannot use duplicate keys.
  • Insertion order is not preserved and the dictionary is based on hashcode of the keys.
  • Indexing and Slicing concepts are not allowed.
  • For both the keys and values, Heterogeneous objects are allowed
  • Dictionary is a mutable Datatype
  • Dictionary is dynamic in nature
  • The key-values are represented inside the curly braces separated by a comma.
  • If we try to use the duplicate keys in the dictionary then the old values will be replaced with the new value.

Example:

dictionary={100:"Apple", "A":300, 200:"pooja",  "orange":400, 100:"Pista"}
print(dictionary)

The output is:

dictionary-operator-python-example

If you observe the above output, here we have used the key value 100 two times but the old key value has been replaced with the new key value.

Python Introduction

Different ways of Creating a Dictionary Objects

We can Create Dictionary Objects in many ways as follows:

Creating an Empty Dictionary:

We can create an empty dictionary in two ways

dictionary={ }
print(type(dictionary))
dictionry= dict()     #by using dict function
print(type(dictionary))                     

The output is:

creating-empty-dictionry

Creating a Dictionary if we know the data already:

If we know the key-value pairs then we can create a dictionary by separating the key and value by a colon and separating each key-value pairs by comma enclosed with curly braces.

dictionry={100:"banana", 300:"Apple", 400:"plum"}
Creating a Dictionary by converting other datatypes using dict() Function:

The following example demonstrates converting a list of tuple values into a dictionary

info=[('a',100),('b',200),('c',300)]
data=dict(info)
print(data)

The output is:

converting-list-of-tuples-into-dict

In the same way, we can convert the following things also:

  • Tuple of Tuple
  • List of Tuple
  • Set of Tuple
  • List of List
  • Tuple of List
But we cannot convert a set of list, because the elements inside the sets are based on hashcode and the elements inside the list are not based on the hashcode and hence it is not possible to convert the set of the list into a tuple.

The following example demonstrates converting a list of list into a tuple

info=[[10,23],[35,50],['R','Q']]
data=dict(info)
print(data)

The output is:

converting-list-of-list-into-dict

And If we try to convert a set of list into a dictionary, then we will get an error

info={[10,23],[35,50],['R','Q']}
data=dict(info)
print(data)

##The output is:
 File "C:/Users/User/.spyder-py3/temp.py", line 1, in <module>
    info={[10,23],[35,50],['R','Q']}

TypeError: unhashable type: 'list'

converting-set-of-list-into-dict

To convert any other datatype into a dictionary, compulsory the internal object should contain two elements, otherwise, Python will throw an error.

Suppose if we want to convert the tuple of a tuple into a dictionary and the tuple object contain three elements internally instead of two elements then

info=((20,30,'A'),(39,60))
data=dict(info)
print(data)
##The output is
 File "C:/Users/User/.spyder-py3/temp.py", line 2, in <module>
    data=dict(info)

ValueError: dictionary update sequence element #0 has length 3; 2 is required

The output is:

converting-tuple-of-tuple-into-dict

Creating a Dictionary by using the Dynamic input

We can create a dictionary using the eval function to enter the input dynamically.

The following example demonstrates the use of eval() function in creating a dictionary

my_info=eval(input("Enter any dictionary:"))
print(my_info)

The output is:

creating-dict-dynamically

Working with IDLE Python

Accessing the Data from the Dictionary

We can access the data from the dictionary by using the different ways such as:

If we want to access the value which is associated with s specific key

dictionary={250:'kitkat', 350:'cadbury', 450:'munch'}
print(dictionary[350])

The output is:

accesing-the-key-value-from-the-dict

If we try to access the key-value which is not present in the given dictionary, then python will throw a key error.

dictionary={250:'kitkat', 350:'cadbury', 450:'munch'}
print(dictionary[600])
#The output is:
File "C:/Users/User/.spyder-py3/temp.py", line 2, in <module>
    print(dictionary[600])

KeyError: 600

The output is:

accesing-the-key-value-from-the-dict-python

The following example demonstrates how to overcome the key error

dictionary={25:"google", 35:"web", 45:"app"}
key=int(input("Enter key to find the value:"))
if key in dictionary:
    print("The corresponding value:",dictionary[key])
else:
    print("The provided key is not available")

The output is:

dictionary-program-python

Console on PyDev

Add/Update data in the Dictionary

We can add/update the dictionary by using the syntax

dictionary[key]=value

Example:

dictionary={25:"google", 35:"web", 45:"app"}
dictionary[55]='robot'
print(dictionary)

The new key-value has been added to the current dictionary

adding-new-key-value-to-the-dictionary

Here I am updating the key value 25 then, the old value google will be replaced with new key-value python

dictionary={25:"google", 35:"web", 45:"app"}
dictionary[25]='python'
print(dictionary)

The output is:

updating-the-dictionary-key-value

Float Datatype

Deleting the Key-value Pair

We can delete the key-value pair from the current dictionary by using the del keyword

The syntax for deleting the key-value pair is

del dictionary[key]=value

Example:

dictionary={25:"google", 35:"web", 45:"app"}
print(dictionary)
del dictionary[25]
print(dictionary)

The corresponding key value of 25 will be deleted from the dictionary

deleting-key-values-from-the-dict

The following example demonstrates creating a dictionary by entering the name and marks into the dictionary and display the information on the screen

info=int(input("Enter number of students:"))
dictionary={}
for i in range(info):
    name=input("Enter the name of the student:")
    marks=int(input("Enter the marks of the student:"))
    dictionary[name]=marks
print(dictionary)

The output is:

program-to-print-the-name-and-marks-of-the-student

If we want to print the above details in the table format

info=int(input("Enter number of students:"))
dictionary={}
for i in range(info):
    name=input("Enter the name of the student:")
    marks=int(input("Enter the marks of the student:"))
    dictionary[name]=marks
    
print('*'*30)
print('Name','		','Marks')
print('*'*30)
for name in dictionary:
    print(name,'		',dictionary[name])

The output is:

printing-student-details-in-table

Python Operator

Operators on Dictionary

The concatenation and Repetition operators do not support for Dictionary datatype.

If we try to concatenate two Dictionaries then python will throw an error

dict1={'A':234,'B':456}
dict2={'C':678,'D':890}
dict3=dict1+dict2
print(dict3)
##The output is:

  File "C:/Users/User/.spyder-py3/temp.py", line 3, in <module>
    dict3=dict1+dict2

TypeError: unsupported operand type(s) for +: 'dict' and 'dict'

The output is

concatenate-two-dict

In the same way, if we try to perform repetition operation on a dictionary, then Python will throw an error

dict1={'A':234,'B':456}
dict2={'C':678,'D':890}
dict3=dict1*3
print(dict3)
##The output is:
 File "C:/Users/User/.spyder-py3/temp.py", line 3, in <module>
    dict3=dict1*3

TypeError: unsupported operand type(s) for *: 'dict' and 'int'

The output is:

performing-repition-operation-on-dictionary

Equality operator on dictionary

python supports the equality operator on the dictionary, the dictionary will return true only when the content of the two dictionaries are same.

dict1={'A':234,'B':456}
dict2={'C':678,'D':890}
dict3={'A':234,'B':456}
dict4=dict1==dict2
dict5=dict1==dict3
print(dict4)
print(dict5)

The output is:

equality-operation-on-dict

Relational Operator on Dictionary

Python does not support the relational operator on the dictionary, if we try to perform a relational operation on the dictionary, then Python will throw a type error

dict1={'A':234,'B':456}
dict2={'C':678,'D':890}
dict3={'A':234,'B':456}
print(dict1>dict2)
print(dict3<dict2)
##The output is:
 File "C:/Users/User/.spyder-py3/temp.py", line 4, in <module>
    print(dict1>dict2)

TypeError: '>' not supported between instances of 'dict' and 'dict'

The output is

relational-operation-on-dict

Membership Operator on Dictionary

The Python supports the membership operator on the dictionary and the membership operator checks for the only key and returns True or False depending on the condition

dict1={234:'A', 456:'B'}
dict2={678:'C',890:'D'}
print(234 in dict1)
print(890 in dict2)
print(678 in dict1)
print(456 in dict2)

The output is:

membership-operator-for-dict

Python Input and Output Statements

Methods and Functions of Dictionary

Functions:

Python provides some built-in functions that we can use on dictionary

The len() function returns the length of the dictionary, each key-pair value adds 1 to the length.

The syntax of the len() function is

len(dictionary)

Example:

dictionary={100:"min", 200:"max", 300:"out-of-range"}
print(len(dictionary))

The output is:

len-function-on-dict

The any() function returns True if even one key in a dictionary has a Boolean value of True

The syntax for the any() function is

any(dictionary)

Example:

dictionary={True:False,"":""}
print(any(dictionary))

The output is:

any-function-returns-true

If any key value is False then any() function will return False

dictionary={False:False,"":""}
print(any(dictionary))

The output is:

any-function-return-false

The all() function returns True only when all the key values in the dictionary have a boolean value of true

The syntax for the all() functon is

all(dictionary)

Example:

dictionary={True:False,1:""}
print(all(dictionary))

The output is:

all-function-returns-true

If anyone key value is False then the all() function returns False

dictionary={False:100,1:""}
print(all(dictionary))

The output is:

all-function-returns-false

The sorted() function returns a sorted sequence of the key-value pairs in the dictionary in the ascending order without modifying the original python dictionary.

The syntax for the sorted() function is:

sorted(dictionary)

Example:

dictionary={10:"apple",3:"",4:"orange",5:"banana"}
print(sorted(dictionary))

The output is:

soreted-function-on-dictionary

Methods:

Python provides some built-in methods that we can use on dictionary

The get() method returns the key-value associated with the specified key.

The syntax for the get() method is

dictionary.get(key)

Example:

dictionary={10:"apple",3:"",4:"orange",5:"banana"}
print(dictionary.get(5))

The output is:

get-method-on-dictionary

If the specified key is not present in the dictionary then the get() method returns None

dictionary={10:"apple",3:"",4:"orange",5:"banana"}
print(dictionary.get(2))

The output is:

get-method-returns-none

The update() method updates the key-value present in the one dictionary to another dictionary

The syntax for the update() method is

dictionary1.update(dictionary2)

Example:

dictionary1={10:"apple",3:"",4:"orange",5:"banana"}
dictionary2={23:"butter",6:"ice-cream",7:"lolly-pop"}
dictionary1.update(dictionary2)
print(dictionary1)

The output is:

update-method-on-dictionry

If the dictionaries are having the duplicate values then the update() method will replace the old key value with the new key-value

dictionary1={10:"apple",3:"",4:"orange",5:"banana"}
dictionary2={23:"butter",10:"ice-cream",7:"lolly-pop"}
dictionary1.update(dictionary2)
print(dictionary1)

The output is:

old-key-value-will-be-updated-with-new-key-value

The keys() method returns the list of keys present in the dictionary

The syntax for the keys() method is:

dictionary.keys()

Example:

dictionary={10:"apple",3:"",4:"orange",5:"banana"}
info=dictionary.keys()
print(info)

The output is:

keys-method-on-dict

Instead of dict_keys, we can print the keys one-by-one as follow

dictionary={10:"apple",3:"",4:"orange",5:"banana"}
info=dictionary.keys()
for key in dictionary.keys():
    print(key)

The output is:

printing-keys-one-by-one

The values() method returns the list of values present in the dictionary

The syntax for the values() method is :

dictionary.values()

Example:

dictionary={10:"apple",3:"",4:"orange",5:"banana"}
info=dictionary.values()
print(info)

The output is:

values-method-for-dictionary

Instead of dict_values, we can print the values one-by-one as follow

dictionary={10:"apple",3:"",4:"orange",5:"banana"}
info=dictionary.values()
for value in dictionary.values():
    print(value)

The output is:

printing-values-one-by-one

The items() method returns each key-value pair as an item present in the dictionary in the form of a list of the tuple.

The syntax for the items() method is:

dictionary.items()

Example:

dictionary={10:"apple",11:"walnut",4:"orange",5:"banana"}
data=dictionary.items()
print(data)

The output is:

accesing-items-from-the-dictionary

Instead of dict_items, we can print the items one-by-one as follow

dictionary={10:"apple",11:"walnut",4:"orange",5:"banana"}
data=dictionary.items()
for item in dictionary.items():
    print(item)

The output is:

accessing-item-from-the-dict

The following program to get the value from the dictionary for the given key

dictionary={10:"apple",11:"walnut",4:"orange",5:"banana"}
key=int(input("Enter key to find the value:"))
if key in dictionary:
    print("The corresponding value:",dictionary.get(key))
else:
    print("The specified key is not available:")    

The output is:

wap-get-the-specified-value

The following program to get the key from the dictionary for the given value

dictionary={100:'Apple', 200:'Banana', 300:'Orange'}
value=input("Enter value to find key:")
available=False
for k,v in dictionary.items():
      if v==value:
          print("The corresponding key:",k)
          available=True
if available==False:
     print("provided value is not found in dictionary")

The output is:

finding-the-key-in-dictionary

This program supports to display all the duplicate values associated with the keys

dictionary={100:'Apple', 200:'Apple', 300:'Apple'}
value=input("Enter value to find key:")
available=False
for k,v in dictionary.items():
      if v==value:
          print("The corresponding key:",k)
          available=True
if available==False:
     print("provided value is not found in dictionary")

The output is:

duplicate-values-associetd-with-keys

The pop() method removes the item associated with the specified key and returns the corresponding value.

If the specified key is not present in the dictionary then the pop() method will throw a key error.

The syntax for the pop() method is

pop(key)

Example:

dictionary={100:'A', 200:'B', 300:'C', 400:'D'}
print(dictionary.pop(300))
print(dictionary)

The output is:

pop-method-on-dict

If the specified key is not available then we are going to get a key error

dictionary={100:'A', 200:'B', 300:'C', 400:'D'}
print(dictionary.pop(500))
print(dictionary)

The output is:

key-error-in-pop-method-on-dict

The popitem() method removes a key-value pair randomly

The syntax for the popitem() method is:

dictionary={100:'A', 200:'B', 300:'C', 400:'D'}
print(dictionary.popitem())

The output is:

removing-item-randomly

If we try to apply popitem() method to an empty dictionary then we will get a key error.

dictionary={}
print(dictionary.popitem())

The output is:

applying-pop-item-method-on-empty-dict

The clear() method is used to remove all the key-value pairs from the dictionary

The syntax for the clear() method is

dictionary.clear()

Example:

dictionary={100:'A', 200:'B', 300:'C', 400:'D'}
dictionary.clear()
print(dictionary)

The output is:

clear-method-on-dict

The setdefault() method returns the new key-value pair to the dictionary if the specified key is not present.

The syntax for the setdefault() method is

setdefault(key,value)

Example:

dictionary={100:'A', 200:'B', 300:'C', 400:'D'}
print(dictionary.setdefault(500,'E'))
print(dictionary)

The output is:

adding-new-key-value-pair-to-the-dictionary

If the specified key is already present then the setdefault() method will keep the old value without replacing it.

dictionary={100:'A', 200:'B', 300:'C', 400:'D'}
print(dictionary.setdefault(200,"bonus"))
print(dictionary)

The output is:

updating-default-value-without-replacing-old value

Command Line Arguments

Aliasing and Cloning of Dictionary Objects

The process of creating a duplicate reference variable to an existing dictionary is called aliasing.

dictionary1={100:'A', 200:'B', 300:'C', 400:'D'}
dictionary2=dictionary1
dictionary1[600]='E'
print(dictionary1)
print(dictionary2)

If we perform any changes to the dictionary1, then that change will be reflecting on the dictionry2 also.

aliasing-concept-on-dictionary

The disadvantage of using aliasing method is that, if we made any changes to the dictionary object by using one reference variable, it will be reflecting in the other reference variable also, so to overcome this problem we can use cloning method.

Cloning is nothing but creating a new object without creating a duplicate reference variable, this can be done by using the copy() method.

dictionary1={100:'A', 200:'B', 300:'C', 400:'D'}
dictionary2=dictionary1.copy()
dictionary1[600]='E'
print(dictionary1)
print(dictionary2)

The output is:

cloning-method-on-dict



Python Flow Control

Programs on Dictionary

1. Write a program to take a dictionary from the keyboard and print the sum of values.

dictionary=eval(input("Enter any dictionary:"))
print("The sum of values:", sum(dictionary.values()))

The output is:

sum-of-values-in-the-dict

2. Write a program to find the number of occurrences of each letter present in the given string.

word=input("Enter any string:")
dictionary={}
for character in word:
    dictionary[character]=dictionary.get(character,0)+1
for key,value in dictionary.items():
    print(key,'Occurs',value,'times')

The output is:

counting-occurences-of-string

3. Write a program to find the number of occurrences of each vowel present in the given string.

word=input("Enter any string:")
vowels={'a','e','i','o','u'}
dictionary={}
for character in word:
      if character in vowels:
          dictionary[character]=dictionary.get(character,0)+1
for key,value in sorted(dictionary.items()):
        print(key,'Occurred',value,'items')

The output is:

counting-vowels-present-in-the-dict

Concatenate and Repeat Operators for String

Dictionary Comprehension

The easy and concise way of creating dictionary objects from any iterable based on some conditions.

The syntax for the Dictionary comprehension is:

Dictionary=[expression for an item in the dictionary if the condition]

Example:

Finding the square values for 1 to 5 between the range(1,6)

dictionary={x:2**x for x in range(1,6)}
print(dictionary)

The output is:

dict-comprehension

Merging of Collection Data Types

Merging of List Objects:

We can merge two list objects into a single list by using the concatenation operation

List1=[19,20,21,22]
List2=[18,23,24,25]
List3=List1+List2
print(List3)

The output is:

merginf-list-objects

Another alternative way of merging a list object is:

List1=[19,20,21,22]
List2=[18,23,24,25]
List3=[*List1,*List2]
print(List3)

The output is:

alternate-way-of-merging-list

Merging of Tuple Objects:

We can merge two Tuple objects into a single Tuple by using the concatenation operation

Tuple1=(19,20,21,22)
Tuple2=(18,23,24,25)
Tuple3=(Tuple1+Tuple2)
print(Tuple3)

The output is:

merging-tuple-objects-one

Another alternative way of merging a Tuple object is:

Tuple1=(19,20,21,22)
Tuple2=(18,23,24,25)
Tuple3=(*Tuple1, *Tuple2)
print(Tuple3)

The output is:

merging-tuple-objects-two

Merging of Set Objects:

We cannot perform merging of two set objects into a single set by using the concatenation operation.

Because python does not support concatenation on Set, if we try to perform concatenation operation then we will get a type error

set1={19,20,21,22}
set2={18,23,24,25}
set3=(set1+set2)
print(set3)

The output is:

performing-concatenation-on-set

We can use another approach to merge two set objects

set1={19,20,21,22}
set2={18,23,24,25}
set3=(*set1,*set2)
print(set3)

The output is:

merging-set-objects-by-using-second-approach

Merging of Dictionary Objects:

We cannot perform merging of two Dictionary objects into a single dictionary by using the concatenation operation.

Because python does not support concatenation on the dictionary, if we try to perform concatenation operation then we will get a type error

dictionary1={19:"A",20:"B",21:"C",22:"D"}
dictionary2={18:"E",23:"F",24:"G",25:"H"}
dictionary3={dictionary1+dictionary2}
print(dictionary3)

The output is:

concatenation-does-not-support-dict

We can use another approach to merge two dictionary objects, we can use ** operand to combine each key-value pair

dictionary1={19:"A",20:"B",21:"C",22:"D"}
dictionary2={18:"E",23:"F",24:"G",25:"H"}
dictionary3={**dictionary1,**dictionary2}
print(dictionary3)

The output is:

combining-dict-objects

Nested Collections:

The collections inside another collection are called as nested collection

Example1:

The below example contains List of tuple objects if we want to access the second element of the first tuple object, we can use the following approach

List=[(10,11,12),(13,14,15)]
print(List[0][1])

The output is :

accesing-list-of-tuple-objects-one

In the same, if we want to access the third element of the second tuple object

List=[(10,11,12),(13,14,15)]
print(List[1][2])

The output is:

accesing-list-of-tuple-objects-two

Example2:

The following example contains a dictionary of tuples If want to access the second value of the first key is as follow:

dictionary={ "cars":("Innova","Honda","Maruthi"),"Mobiles":("Samsung","Nokia","Oppo")}
print(dictionary["cars"][1])

The output is:

accessing-dict-of-tuple-object-one

We can access the same data with another approach

dictionary={ "cars":("Innova","Honda","Maruthi"),"Mobiles":("Samsung","Nokia","Oppo")}
print(dictionary.get("cars")[1])

The output is:

accessing-dict-of-tuple-object-two

In the same way, to access the value associated with the mobile is as follow

dictionary={ "cars":("Innova","Honda","Maruthi"),"Mobiles":("Samsung","Nokia","Oppo")}
for mobile in dictionary.get("Mobiles"):
    print(mobile)

The output is:

accessing-mobile-values

Conclusion:

We cannot add the list inside the set as an object because the set is based on hashcode and list is not based on the hashcode and hence we cannot use list inside the set

set={(10,20,30),[40,50,60]}
print(set)

The output is:

list-inside-set

Similarly, we cannot add the list as a key to the dictionary because the tuple is based on hashcode but the list is not based on the hashcode

dictionary={(10,20,30):"item1",[40,50,60]:"item2"}
print(dictionary)

The output is:

using-list-inside-dict









Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions