Dictionary Methods in Python | Install 2 (update (), has_key (), fromkeys () …)



# Python code to demonstrate how it works
# fromkeys () and update ()

 
# Initializing dictionary 1

dic1 = { ` Name` : `Nandini` , `Age` : 19 }

 
# Initializing Dictionary 2

dic2 = { `ID` : 2541997 }

 
# Initializing sequence

sequ = ( ` Name` , `Age` , `ID` )

  
# using update to add dic2 values ​​to dic 1
dic1.update (dic2)

 
# print updated dictionary values ​​

print ( "The updated dictionary is:" )

print ( str (dic1))

 
# using fromkeys () to convert sequence to dictionary

dict = dict . fromkeys (sequ, 5 )

 
# print new dictionary values ​​

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 the specified dictionary is in the dictionary, otherwise it returns false.

4. get (key, def_val) : — This function returns the key value associated with the key mentioned in the arguments. If the key is missing, the default is returned.

# Python code to demonstrate how it works
# has_key () and get ()

 
# Dictionary initialization

dict = { `Name` : ` Nandini` , `Age` : 19 }

  
# using has_key () to check if there is dic1 has a key

if dict . has_key (  `Name` ):

  print ( "Name is a key" )

else : print ( "Name is not a key" )

 
# using get () to print the key value

print ( "The value associated with ID is:" )

print ( dict . get ( `ID` , "Not Present" ))

 
# print dictionary values ​​

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 looks for a key and displays its value like get (), but creates a new key with def_value if the key is missing.

# Python code to demonstrate how it works
# set as default ()

 
# Initializing the dictionary

dict = { `Name` : `Nandini` , ` Age` : 19 }

 
# using setdefault () to print the key value

print ( "The value associated with Age is:" , end = "")

print ( dict . setdefault ( `ID` , " No ID " ))

  
# print dictionary values ​​

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`} 

This article is courtesy of Manjeet Singh . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.