pythonDictionary.py
# Dictionary - Python
from pip.utils.hashes import FAVORITE_HASH
from email.policy import default
studentInfo = {'rollNo':123,'name':'Avinash','age':8,'class':'III'}
print('*****Student
Info*****')
print('Roll No:
',studentInfo['rollNo'],'\nName: ',studentInfo['name'],
'\nAge; ',studentInfo['age'],'\nClass:
',studentInfo['class'])
fav = {'color':'Violet','fruit':'apple','animal':'tiger'}
print('\nFavourites:
',fav)
#dictionary functions
print('String
representation: ',str(fav))
print('Length: ',len(fav))
print('Type: ',type(fav))
#copying a dictionary
fav_2 = dict.copy(fav)
print('fav_2 -
copy of fav: ',fav_2)
#access the value by its key
print('Value of
color: ',fav.get('color'))
#check if the key exits in the dictionary
print("Is
the key fruit exists:", 'fruit' in fav)
#print the list of values in a
dictionary
print('Values
of fav: ',fav.values())
#print the list of key in a
dictionary
print("Keys
of fav: ",fav.keys())
#print the list of items in a
dictionary
print("Items
of fav: ",fav.items())
#create a dictionary from keys
from another dictionary with default value none
fav_3 = dict.fromkeys(fav)
print("fav_3:
",fav_3)
#clear a dictionary
dict.clear(fav_3)
print('fav_3
after clear: ',fav_3)
#update a dictionary with another
dictionary value pair
fav_3.update(fav_2)
print('fav_3
after updating with fav_2: ',fav_3)
#adds a key if not present
fav_3.setdefault('place')
print('fav_3
after setdefault key: ',fav_3)
output:
*****Student Info*****
Roll No: 123
Name: Avinash
Age; 8
Class: III
Favourites: {'color':
'Violet', 'fruit': 'apple', 'animal': 'tiger'}
String representation: {'color':
'Violet', 'fruit': 'apple', 'animal': 'tiger'}
Length: 3
Type: <class 'dict'>
fav_2 - copy of fav: {'color':
'Violet', 'fruit': 'apple', 'animal': 'tiger'}
Value of color: Violet
Is the key fruit exists: True
Values of fav: dict_values(['Violet',
'apple', 'tiger'])
Keys of fav: dict_keys(['color',
'fruit', 'animal'])
Items of fav: dict_items([('color',
'Violet'), ('fruit', 'apple'), ('animal', 'tiger')])
fav_3: {'color': None,
'fruit': None, 'animal': None}
fav_3 after clear: {}
fav_3 after updating with fav_2: {'color':
'Violet', 'fruit': 'apple', 'animal': 'tiger'}
fav_3 after setdefault key: {'color':
'Violet', 'fruit': 'apple', 'animal': 'tiger', 'place': None}