Python Dictionary Methods Flashcards
clear()
The clear() method removes all the elements from a dictionary.
dictionary.clear()
car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
}
car.clear()
copy()
The copy() method returns a copy of the specified dictionary.
dictionary.copy()
car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
}
x = car.copy()
fromkeys()
The fromkeys() method returns a dictionary with the specified keys and the specified value.
dict.fromkeys(keys, value)
x = ('key1', 'key2', 'key3') y = 0
thisdict = dict.fromkeys(x, y)
print(thisdict)
get()
The get() method returns the value of the item with the specified key.
dictionary.get(keyname, value)
car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
}
x = car.get(“model”)
items()
The items() method returns a view object. The view object contains the key-value pairs of the dictionary, as tuples in a list.
dictionary.items()
car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
}
x = car.items()
keys()
The keys() method returns a view object. The view object contains the keys of the dictionary, as a list.
dictionary.keys()
car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
}
x = car.keys()
pop()
The pop() method removes the specified item from the dictionary.
dictionary.pop(keyname, defaultvalue)
car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
}
car.pop(“model”)
popitem()
The popitem() method removes the item that was last inserted into the dictionary. In versions before 3.7, the popitem() method removes a random item.
dictionary.popitem()
car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
}
car.popitem()
setdefault()
The setdefault() method returns the value of the item with the specified key.
dictionary.setdefault(keyname, value)
car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
}
x = car.setdefault(“model”, “Bronco”)
update()
The update() method inserts the specified items to the dictionary.
dictionary.update(iterable)
car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
}
car.update({“color”: “White”})
values()
The values() method returns a view object. The view object contains the values of the dictionary, as a list.
dictionary.values()
car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
}
x = car.values()