1/14
Flashcards covering key concepts of Python dictionaries, including creation, manipulation, and methods.
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
Dictionary
An object that stores a collection of data in key-value pairs. Keys must be immutable objects.
Retrieving a Value
Use dictionary[key]. Raises KeyError if key is not found. Use 'in' and 'not in' to check for key existence.
Adding Elements
Dictionaries are mutable. Add key-value pairs using dictionary[key] = value. Overwrites if key exists.
Deleting Elements
Use del dictionary[key]. Raises KeyError if key is not found.
len() function
Used to obtain the number of elements in a dictionary.
Key Constraints
Keys must be immutable objects, but values can be of any type.
Creating Empty Dictionary
Use {} or dict(). Add elements as program executes.
Iterating with For Loop
Use for key in dictionary: to iterate over keys.
clear() method
Deletes all elements in a dictionary, making it empty.
get() method
Returns value associated with specified key. Returns default (or None) if key is not found, avoiding KeyError.
items() method
Returns all keys and their associated values as a dictionary view (sequence of tuples).
keys() method
Returns all the dictionary's keys as a sequence.
values() method
Returns all the dictionary's values as a sequence.
pop() method
Returns value associated with specified key and removes the key-value pair. Optional default value if key not found.
popitem() method
Returns and removes the last added key-value pair as a tuple.