List of Topics:
Research Breakthrough Possible @S-Logix pro@slogix.in

Office Address

Social List

What are the Methods of Dictionary in Python?

Methods of Dictionary using Python

Condition for Methods of Dictionary in Python

  • Description: A dictionary is a collection of key-value pairs.It comes with several built-in methods that allow you to manipulate and interact with the data effectively.
Step-by-Step Process
  • get(): Retrieve the value of a key, with an optional default if the key doesn’t exist.
  • keys(): Get all the keys in the dictionary.
  • values(): Get all the values in the dictionary.
  • items(): Get all key-value pairs as tuples.
  • update(): Add or update key-value pairs from another dictionary.
  • pop(): Remove a key and return its value.
  • popitem(): Remove and return the last key-value pair.
  • clear(): Remove all items from the dictionary.
  • copy(): Create a shallow copy of the dictionary.
Sample Code
  • #Using get()
    my_dict = {'name': 'Kumar', 'age': 25}
    print("Output for get:")
    print(my_dict.get('name'))
    print(my_dict.get('gender', 'Not Found'))
    print()
    #Using keys()
    my_dict = {'a': 1, 'b': 2}
    print("Output for keys:")
    print(my_dict.keys())
    print()
    #Using values()
    my_dict = {'a': 1, 'b': 2}
    print("Output for values:")
    print(my_dict.values())
    print()
    #Using items()
    my_dict = {'a': 1, 'b': 2}
    print("Output for items:")
    print(my_dict.items())
    print()
    #Using update()
    my_dict = {'a': 1}
    my_dict.update({'b': 2, 'c': 3})
    print("Output for update:")
    print(my_dict)
    print()
    #Using pop()
    my_dict = {'a': 1, 'b': 2}
    value = my_dict.pop('a')
    print("Output for pop:")
    print(value)
    print(my_dict)
    print()
    #Using popitem()
    my_dict = {'a': 1, 'b': 2}
    item = my_dict.popitem()
    print("Output for popitem:")
    print(item)
    print(my_dict)
    print()
    #Using clear()
    my_dict = {'a': 1, 'b': 2}
    my_dict.clear()
    print("Output for clear:")
    print(my_dict)
    print()
    #Using copy()
    my_dict = {'a': 1, 'b': 2}
    new_dict = my_dict.copy()
    print("Output for copy:")
    print(new_dict)
Screenshots
  •  Methods of Dictionary