Python Dictionary Methods

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

  1. 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’])

  1. 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’])
  1. 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’)])
  2. 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’
  3. 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

Leave a Comment

Your email address will not be published. Required fields are marked *

Open chat
Need Help?
Hello
Can we Help you?