Python Dictionary Methods

In this lesson we want to talk about Python Dictionary Methods. 

 

What is Python Dictionary ?

Python dictionary is collection of key value pairs, where each key is mapped to specific value. Dictionaries are also known as associative arrays or maps in other programming languages.

 

In Python, dictionaries are defined using curly braces {} and are composed of key value pairs separated by colons :. for example:

In this example, 'name', 'age', and 'gender' are the keys, and 'John', 32, and 'male' are the values associated with those keys.

 

Dictionaries are unordered and mutable, meaning that you can add, remove and modify elements in a dictionary after it has been created. they are also optimized for fast lookups, making them useful for data that needs to be quickly retrieved based on specific key.

 

 

Learn More on Python

 

 

 

Python Dictionary Methods

Python dictionaries have several built in methods that allow you to perform common operations on dictionaries. some of the most commonly used dictionary methods include:

  • dict.clear(): Removes all items from the dictionary.
  • dict.copy(): Returns a shallow copy of the dictionary.
  • dict.fromkeys(keys, value): Returns a new dictionary with the specified keys and each key mapped to the specified value.
  • dict.get(key, default): Returns value associated with the specified key or the default value if the key is not found.
  • dict.items(): Returns view of the dictionary’s (key, value) pairs as a list of tuple.
  • dict.keys(): Returns a view of the dictionary’s keys.
  • dict.pop(key, default): Removes specified key and returns its value or the default value if the key is not found.
  • dict.update(other_dict): Adds the items from the other_dict to the dictionary, overwriting any existing values for matching keys.
  • dict.values(): Returns a view of the dictionary’s values.

 

 

This is an example of using some of the dictionary methods:

In this example, we define a dictionary person with keys 'name', 'age', and 'gender'. We then use the items(), keys(), and values() methods to get views of the dictionary’s items, keys, and values, respectively. Finally, we use the get() method to retrieve the value associated with the 'age' key.

 

 

 

Run the code and this will be the result

Python Dictionary Methods
Python Dictionary Methods

Leave a Comment