Dictionary Methods in Python | Set to 1 (cmp (), len (), items () …)



Dictionary

Some dictionary methods are discussed in this article.

1. str (dic) : — This method is used to return a string denoting all the dictionary keys with their values.

2. items () : — This method is used to return a list with all dictionary keys with values.

# Python code to demonstrate how it works
# str () and items ()

 
# Initializing the dictionary

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

 
# using str () to display dic as a string

print ( "The constituents of dictionary as string are:" )

print ( str (dic))

 
# using str () to display dic as a list

print ( "The constituents of dictionary as list are:" )

print (dic.items ())

Output:

 The constituents of dictionary as string are: {`Name`:` Nandini`, `Age`: 19} The constituents of dictionary as list are: dict_items ([(` Name`, `Nandini`), (` Age`, 19)])  

3. len () : — returns number of key objects dictionary elements.

4. type () : — This function returns the data type of the argument.

# Python code to demonstrate how it works
# len () and type ()

 
# Dictionary initialization

dic = { `Name` : ` Nandini` , ` Age` : 19 , `ID` : 2541997 }

 
# Initializing list

li = [ 1 , 3 , 5 , 6 ]

 
# using len () to display the dic size

print ( "The size of dic is:" , end = "")

print ( len (dic))

 
# using type () to display the data type

print (  "The data type of dic is:" , end = "")

print ( type (dic))

 
# using type () to display the data type

print ( "The data type of li is:" , end = "")

print ( type (li))

Output:

 The size of dic is: 3 The data type of dic is: The data type of li is: 

5. copy () : — This function creates a shallow copy of a dictionary into another dictionary.

6. clear () : — This function is used to clear the contents of a dictionary .

# Python code to demonstrate how it works
# clear () and copy ()

 
# Initializing the dictionary

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

  
# Initializing the dictionary

dic3 = {}

  
# using copy () to create a shallow copy of the dictionary

dic3 = dic1.copy ()

  
# print new dictionary

print ( "The new copied dictionary is:" )

print (dic3.items ())

 
# clear dictionary
dic1.clear ()

 
# print the empty dictionary

print ( "The contents of deleted dictionary is:" , end = "")

print (dic1.items ())

Output:

 The new copied dictionary is: dict_items ([(`Age`, 19), (` Name`, `Nandini`)]) The contents of deleted dictionary is: dict_items ([]) 

This article 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.