Complete Python Dictionary cheatsheet with clear examples for quick revision
Example: my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
Removes all items from the dictionary.
my_dict.clear() # {}
Creates a copy of a dictionary.
new_dict = my_dict.copy() # {'name':'John', 'age':25, 'city':'New York'}
Returns the value of a particular key.
my_dict.get('age') # 25
Returns all the items present in the dictionary as (key, value) pairs.
my_dict.items() # (name, john), (age, 25), (city, New York)
Returns a list of keys in a dictionary.
my_dict.keys() # [name, age, city]
Returns a list of values in a dictionary.
my_dict.values() # [john, 25, new york]
Removes the key-value pair from the dictionary.
my_dict.pop('age') # {'name': 'John', 'city': 'New York'}
Removes the last key-value pair from the dictionary.
my_dict.popitem() # {'name': 'John', 'age': 25}
Updates a dictionary by adding the items from another dictionary.
new_dict = {'country':'USA', 'mob_num':12345} my_dict.update(new_dict) # {'name': 'John', 'age': 25, 'city': ' New York', 'country':'USA', 'mob_num':12345}
Returns the value for a key if it exists. If not, inserts the key with a value of default and returns default.
my_dict.setdefault('age', 30) # {'name': 'John', 'age': 25, 'city': 'New York'} my_dict.setdefault('height', 175) # {'name': 'John', 'age': 25, 'city': 'New York', 'height', 175}
Creates a new dictionary with keys from iterable and values set to value.
new_dict = dict.fromkeys(['a', 'b', 'c'], 0) # {'a': 0, 'b': 0, 'c': 0}