Dictionary_Methods_Python
Dictionary_Methods_Python
Example:
2. Removing Items
- pop(key): Removes key and returns its value. Raises KeyError if key doesn't exist.
- popitem(): Removes and returns the last inserted key-value pair (LIFO order in Python 3.7+).
- del dict[key]: Deletes key-value pair. Raises KeyError if key doesn't exist.
Example:
my_dict.pop("age") # Returns 25
3. Accessing Items
- get(key, default): Returns value for the key; returns default if key isn't found.
Example:
print(my_dict.get("name")) # Alice
print(my_dict.get("address", "Not Found")) # Not Found
4. Checking Keys
Example:
5. Copying a Dictionary
Example:
copy_dict = original.copy()
6. Merging Dictionaries
- update(other_dict): Adds key-value pairs from another dictionary, updating existing keys.
Example:
- setdefault(key, default): Returns the value of the key if it exists, otherwise sets it to default and
returns it.
Example:
- fromkeys(iterable, value): Creates a new dictionary from a list of keys with a specified value.
Example:
9. Dictionary Comprehension
Example: