Dictionaries Flashcards
Create a dictionary
dictionary = { “key1”: “value1”, “key2”: “value2”}
Access value by key in dictionary
dictionary[“key1”]
Add of update key value pair
dictionary[“key3”] = “value3”
Delete key value pair
del dictionary[“key1”]
Check if key exists
‘key1’ in dictionary
Get list of keys in dictionary
list(dictionary.keys())
Get list of values in dictionary
list(dictionary.values())
Update dictionary with elements from another dictionary, if key already exists, its value is updated, if the key doesn’t exist, it is added
dictionary.update(another_dictionary)
If key doesn’t exist set default value
dictionary.setdefault(‘key’, ‘default_value’)
Create a dictionary from array of keys with default value
dict.fromkeys(arr, value)
Remove key from dictionary and return value
dictionary.pop(‘key’)
Remove and return the last inserted key-value pair as a tuple
key, value = dictionary.popitem()
Loop through keys in dictionary
for key in my_dict:
print(key)
Loop through both key and value in dictionary
for key, value in my_dict.items():
print(key, value)