Python Dictionary Methods
1.Get (Key) :It Returns the value associated with the specified Key
Examaple:
my_dict = {“name”: ”Ravi”,“age”: 24 , “city”: ”Hyderabad” }
print(my_dict.get(“age”))
output:24
- key(): It returns all the keys containing in the dictionary.
Example :
my_dict = {“name”: ”Ravi”, “age”: 24 ,“city”: ”Hyderabad” }
print(my_dict.keys())
output: dict_keys([‘name’ ,’age’ ’ city’])
- values(): It returns all the values from the dictionary object.
Example:
my_dict = {“name”: ”Ravi”, “age”: 24 ,“city”: ”Hyderabad” }
print(my_dict.values())
output: dict_values([‘Ravi’, 24 , ‘Hyderabad’])
- items() : It returns all the key-value pairs of the dictionary as tuples. Example:
my_dict = {“name”: ”Ravi”, “age”: 24 ,“city”: ”Hyderabad” }
print(my_dict.items())
output: dict_items([(‘name’, ’Ravi’ ) , (‘age’ , 24) ,(‘city’, ’Hyderabad’)]) - update() : It inserts the specified items to the dictionary.
Example:
my_dict = {“name”: ”Ravi”, “age”: 24 ,“city”: ”Hyderabad” }
my_dict.update({‘gender’:’male’})
print(my_dict)
output: {‘name’:’Ravi’, ’age’:24 ,‘city’ : ‘Hyderabad’, ‘gender’:’male’ - pop( ) & popitem ( ) :
pop( ): Removes the element with specified key
popitem ( ): Remove the last inserted key-value pair
Example : my_dict = {“name”: “ramu”, “age”: 30,”city”: “Hyderabad”}
removed_value = my_dict.pop(“age”)
print(“Removed value:”, removed_value)
removed_item = my_dict.popitem()
print(“Removed item:”, removed_item)
Output: Removed value: 30 #here the age value will be deleted by using pop
Output: Removed item: (‘city’, ‘ Hyderabad’) #here the key and values are removed by using popitem