Dictionary Methods ( Part 2 )
Last Updated :
14 Jul, 2022
1. fromkeys(seq,value) :- This method is used to declare a new dictionary from the sequence mentioned in its arguments. This function can also initialize the declared dictionary with “value” argument.
2. update(dic) :- This function is used to update the dictionary to add other dictionary keys.
dic1 = { 'Name' : 'Nandini' , 'Age' : 19 }
dic2 = { 'ID' : 2541997 }
sequ = ( 'Name' , 'Age' , 'ID' )
dic1.update(dic2)
print ( "The updated dictionary is : " )
print ( str (dic1))
dict = dict .fromkeys(sequ, 5 )
print ( "The new dictionary values are : " )
print ( str ( dict ))
|
Output:
The updated dictionary is :
{'Age': 19, 'Name': 'Nandini', 'ID': 2541997}
The new dictionary values are :
{'Age': 5, 'Name': 5, 'ID': 5}
3. has_key() :- This function returns true if specified key is present in the dictionary, else returns false.
4. get(key, def_val) :- This function return the key value associated with the key mentioned in arguments. If key is not present, the default value is returned.
dict = { 'Name' : 'Nandini' , 'Age' : 19 }
if dict .has_key( 'Name' ):
print ( "Name is a key" )
else : print ( "Name is not a key" )
print ( "The value associated with ID is : " )
print ( dict .get( 'ID' , "Not Present" ))
print ( "The dictionary values are : " )
print ( str ( dict ))
|
Output:
Name is a key
The value associated with ID is :
Not Present
The dictionary values are :
{'Name': 'Nandini', 'Age': 19}
5. setdefault(key, def_value) :- This function also searches for a key and displays its value like get() but, it creates new key with def_value if key is not present.
dict = { 'Name' : 'Nandini' , 'Age' : 19 }
print ( "The value associated with Age is : " ,end = "")
print ( dict .setdefault( 'ID' , "No ID" ))
print ( "The dictionary values are : " )
print ( str ( dict ))
|
Output:
The value associated with Age is : No ID
The dictionary values are :
{'Name': 'Nandini', 'Age': 19, 'ID': 'No ID'}
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...