DEV Community

Cover image for Python dictionary methods😀😀⚡
Ajith R
Ajith R

Posted on

Python dictionary methods😀😀⚡

.get(key)
The get() method returns the value of the item with the specified key. you can also pass a optional parameter value to return if the specified key does not exist othervise it returns None.

# create dictionary dict ={"k1":"V1", "k2":"V2","k3":"V3"}
# using get method print(dict.get("k1"), end=" print(dict.get("k5")) ")
# Output: VI
None
Enter fullscreen mode Exit fullscreen mode

.items()
The items() method returns a view object. The view object contains the key-value pairs of the dictionary, as tuples in a list.

# using items method
dict = {"kl":"V1", "k2":"V2","k3":"V3"} print(dict.items())
# Output : dict_items([('k1', 'V1'), ('k2', 'V2'), ('k3', 'V3')])
Enter fullscreen mode Exit fullscreen mode

.keys()
The keys() method returns a view object. The view object contains the keys of the dictionary, as a list.

# using keys method
dict = {"kl":"V1", "k2":"V2","k3":"V3"}
print(dict.keys())
# Output :
dict_keys(['kl', 'k2', 'k3'])
Enter fullscreen mode Exit fullscreen mode

.values()
The values() method returns a view object. The view object contains the values of the dictionary, as a list.

# using values method dict = {"kl":"V1", "k2":"V2","k3":"V3"}
print(dict.values())
# Output: dict_values(['V1', 'V2', 'V3'])
Enter fullscreen mode Exit fullscreen mode

.pop(key)
The pop method removes the specified item from the dictionary. The value of the removed item is the return value of the pop() method.

# using pop method
dict = {"k1":"V1", "k2":"V2", "k3":"V3"}
print(dict) # Before pop operation value = dict.pop("k2") print(dict) # after pop operation
# Output:
{'k1': 'V1', 'k2': 'V2', 'k3': 'V3'} {'k1': 'V1', 'k3': 'V3'}

Enter fullscreen mode Exit fullscreen mode

.update(dictionary)
The update() method inserts the specified items to the dictionary. The specified items can be a dictionary, or an iterable object with key value pairs.

# using update method
"k2":"V2","k3":"V3"} dict = {"kl":"V1", "k2":"V2", "k3":"V3"}
dict.update({"k4":"V4"}) print(dict)
# Output :
{'kl':'V1', 'k2': 'V2', 'k3':'V3','k4': 'V4'}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)