Quick actions

cmd+k|ctrl+k

Navigation

Languages

dict methods

Snippet info

Language

Python

Visibility

public

Author

narutouzumakiramen18

Created

2026-05-08T01:21:04.731217Z

Updated

2026-05-08T01:21:04.731217Z

# get method is used to get a value that is inside a dict. This is quite useful because -
# When we call a key in the dict that does not exist suppose 'age', if we say print age from this dict.
# Then we know this dict does not have a age key, This throws an error.
# If we are in a video game and we want something that does not exist like magic potions - The game crashes
# This is avoided using get method instead of regular calling. This certainly returns a value None.
# The program continues normally and we can also set a default value for the key we are calling!
dictionary = {
    'basket': [1,2,3],
    'greet': "hello"
}

print(dictionary.get('age',55)) # 55 is the default value.

# Another way of creating dict
user = dict(name = 'naruto')
print(user)

# To check if the key:value pair is in the data structure
print('age' in dictionary)
print('basket' in dictionary)

# To only look for keys.
# .keys() method
# To grab or look for only values.
# .values() method
# To look at everything in general
# .items() method 

# If we clear the information in the first user - The copy is not going to change.
user = dictionary.copy()
print(user)

# pop removes the actual value
print(user.pop('greet'))
print(user)

# To randomly pop a key:value pair - 'popitem'
print(dictionary.popitem())
print(dictionary)
# Modern python does not removes it randomly as this function was updated in python 3.7
# To remove the last key:Value pair that was inserted into the dict.

# To update a item or enter a new item we use the update method.
print(dictionary.update({'age':55})) # we don't have a key called age.
print(dictionary)
INFO