Python Dict Methods Flashcards
dict[key] = value
add or update a value in dictionary
update()
updates the dict with the key-value pairs from another dictionary or iterable.
# Initial dictionary
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
Dictionary with updates
updates = {‘b’: 20, ‘d’: 4}
Update my_dict with updates
my_dict.update(updates)
print(my_dict) # Output: {‘a’: 1, ‘b’: 20, ‘c’: 3, ‘d’: 4}
get()
Returns the value of a specified key
keys()
Returns a list of containing the keys of the dict.
values()
Returns a list of the values of a dict.
items()
Returns a list of keys and values containing the key-value pairs of the dict as tuples.
pop()
Removes and returns the value associated with the specified key
del dict[key]
delete the item with the specified key
in/ not in
checking the membership
copy()
Returns the shallow copy of the dictionary
clear()
Removes all items from the dictionary
len()
Returns the number of items in the dictionary.
sorted()
Returns a new dictionary sorted by keys