In Python, dictionary methods are built-in functions that operate on dictionary objects. These methods provide a variety of operations for modifying, searching, and extracting information from dictionaries. Here are some common dictionary methods:
dict.clear()
:
mythonCopy codemy_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict.clear() # Result: {}
dict.copy()
:
my_dict = {'a': 1, 'b': 2, 'c': 3}
copied_dict = my_dict.copy() # Result: {'a': 1, 'b': 2, 'c': 3}
dict.fromkeys(iterable[, value])
:
None
).keys = ['a', 'b', 'c']
my_dict = dict.fromkeys(keys, 0) # Result: {'a': 0, 'b': 0, 'c': 0}
dict.get(key[, default])
:
None
).my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.get('b') # Result: 2
dict.items()
:
my_dict = {'a': 1, 'b': 2, 'c': 3}
items = my_dict.items() # Result: dict_items([('a', 1), ('b', 2), ('c', 3)])
dict.keys()
:
my_dict = {'a': 1, 'b': 2, 'c': 3}
keys = my_dict.keys() # Result: dict_keys(['a', 'b', 'c'])
dict.values()
:
my_dict = {'a': 1, 'b': 2, 'c': 3}
values = my_dict.values() # Result: dict_values([1, 2, 3])
dict.pop(key[, default])
:
KeyError
if no default is provided).my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.pop('b') # Result: 2, my_dict is now {'a': 1, 'c': 3}
dict.popitem()
:
my_dict = {'a': 1, 'b': 2, 'c': 3}
item = my_dict.popitem() # Result: ('a', 1), my_dict is now {'b': 2, 'c': 3}
dict.setdefault(key[, default])
:
None
if no default is provided) into the dictionary.my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.setdefault('b', 0) # Result: 2, my_dict is unchanged
value2 = my_dict.setdefault('d', 0) # Result: 0, my_dict is now {'a': 1, 'b': 2, 'c': 3, 'd': 0}
dict.update([iterable])
: - Updates the dictionary with key-value pairs from the iterable. If a key already exists, its value is updated.my_dict = {'a': 1, 'b': 2}
my_dict.update({'b': 3, 'c': 4}) # Result: {'a': 1, 'b': 3, 'c': 4}
These are just a few examples of the many dictionary methods available in Python. Dictionary methods provide powerful tools for working with dictionaries and are instrumental in various programming tasks.