python dictionary methods
get()
- Returns the value of the specified key
fruits = {'grape': 'π', 'Watermelon': 'π', 'banana': 'π', 'mango': 'π₯', 'apple': 'π'}
x = fruits.get("mango")
# output
π₯
clear()
- Removes all the elements from the dictionary
fruits = {'grape': 'π', 'Watermelon': 'π', 'banana': 'π', 'mango': 'π₯', 'apple': 'π'}
fruits.clear()
# output
{}
copy()
- Returns a copy of the dictionary
fruits = {'grape': 'π', 'Watermelon': 'π', 'banana': 'π', 'mango': 'π₯', 'apple': 'π'}
x = fruits.copy()
# output
{'grape': 'π', 'Watermelon': 'π', 'banana': 'π', 'mango': 'π₯', 'apple': 'π'}
keys()
- Returns a list containing the dictionary's keys
fruits = {'grape': 'π', 'Watermelon': 'π', 'banana': 'π', 'mango': 'π₯', 'apple': 'π'}
x = fruits.keys()
# output
dict_keys(['grape', 'Watermelon', 'banana', 'mango', 'apple'])
update()
- Updates the dictionary with the specified key-value pairs
fruits = {'grape': 'π', 'Watermelon': 'π', 'banana': 'π', 'mango': 'π₯', 'apple': 'π'}
fruits.update({"strawberry":"π"})
# output
{'grape': 'π', 'Watermelon': 'π', 'banana': 'π', 'mango': 'π₯', 'apple': 'π', 'strawberry': 'π' }
values()
- Returns a list of all the values in the dictionary
fruits = {'grape': 'π', 'Watermelon': 'π', 'banana': 'π', 'mango': 'π₯', 'apple': 'π'}
x = fruits.values()
# output
dict_values(['π', 'π', 'π', 'π₯', 'π'])
pop()
- Removes the element with the specified key
fruits = {'grape': 'π', 'Watermelon': 'π', 'banana': 'π', 'mango': 'π₯', 'apple': 'π'}
fruits.pop('Watermelon')
# output
{'grape': 'π', 'banana': 'π', 'mango': 'π₯', 'apple': 'π'}
items()
- Returns a list containing a tuple for each key value pair
fruits = {'grape': 'π', 'Watermelon': 'π', 'banana': 'π', 'mango': 'π₯', 'apple': 'π'}
x = fruits.items()
# output
dict_items([('grape', 'π'), ('Watermelon', 'π'), ('banana', 'π'), ('mango', 'π₯'), ('apple', 'π' )])
fromkeys()
- Returns a dictionary with the specified keys and value
x = ['grape1', 'grape2', 'grape3']
y = 'π'
fruits = dict.fromkeys(x, y)
# output
{'grape1': 'π', 'grape2': 'π', 'grape3': 'π'}
popitem()
- Removes the last inserted key-value pair
fruits = {'grape': 'π', 'Watermelon': 'π', 'banana': 'π', 'mango': 'π₯', 'apple': 'π'}
fruits.popitem()
# output
{'grape': 'π', 'Watermelon': 'π', 'banana': 'π', 'mango': 'π₯'}
setdefault()
- Returns the value of the specified key.
- If the key does not exist: insert the key, with the specified value.
fruits = {'grape': 'π', 'Watermelon': 'π', 'banana': 'π', 'mango': 'π₯', 'apple': 'π'}
x = fruits.setdefault("grape", None)
# output
{'grape': 'π', 'Watermelon': 'π', 'banana': 'π', 'mango': 'π₯', 'apple': 'π'}
All the best to you.
Top comments (0)