payment by upi: sinhamit@icici or payment by bank account name: amit kumar sinha, account number: 2646728782 IFSC code: KKBK0005660 SWIFT: KKBKINBB

Please support if you like my work by payment through upi: sinhamit@icici or payment by bank

account name: Amit Kumar Sinha,
account number: 2646728782
IFSC code: KKBK0005660
SWIFT: KKBKINBB


Dictionary Methods   in Category: Python   by amit

🕙 Posted on 2023-08-23 at 00:08:04     Read in Hindi ...


Dictionary Methods

    You have already seen in previous page that how an item/element in a dictionary literal can be accessed through its respective key name. A key name in a dictionary literal can be '' (an empty string − a pair of single/double quotes without any blank space) or ' ' (a pair of single/double quotes with a blank space) or other string literal. A key name can be None, True or False, or any numeric (integer/float) value, or tuple literal (which has only immutable items in it). However, you should write meaningful name of any key in a dictionary literal, so that the program (code) doesn't become senseless, and later you may not struggle accessing different items through those keys!

Example 1

my_dict = {'': 'abc', None: 22, 'key': ['def', 'ghi']}
print( my_dict[''] )   # Outputs abc − accessing the item through key name
print( my_dict['key'] )   # Outputs ['def', 'ghi']

print( my_dict['one'] )   # Outputs KeyError: 'one'
print( my_dict[0] )   # Outputs KeyError: 0 (Comment above statement to see result of this line.)

print( my_dict['key'][1] )   # Outputs ghi (Comment above two statements to see result of this line.)
print( my_dict['key'][2] )   # Outputs IndexError: list index out of range

get(self, key, default=None, /)

    When any key doesn't exist in a dictionary literal, the above way to access an item/element from the dictionary, will throw KeyError. Therefore, it is safe to use the get() dictionary method that returns None when that key (for example, 'one' or 0 in above example,) is not present. The third item of my_dict (variable name, assigned with a dictionary literal) in above example, is a nested list. Therefore, first pair of square brackets (in lines 8 and 9 of above example,) contains the key name, and the second pair of square brackets (in those lines) contains the index number.

Example 1 continued ...

print( my_dict.get('one', 'Not Found') )   # Outputs Not Found ('Not Found' is a string data-type. Comment those statements in above example, which show ERRORs to see result of this line.)

print( my_dict.get('key', False)[0] )   # Outputs def because the parent item is returned as nested list from the my_dict dictionary literal. You can also use False (boolean literal) or 0 (zero, integer literal) as second argument, as per your choice.

    The returned item/element from the get() method is very important. That is, if the returned item is an integer, a float, or a boolean value, then placing the [0] after the parentheses (as described above) will throw ERROR, because these are non-sequence data-types. Similary, if the returned item is a nested dictionary, then you have to provide key name in the pair of square brackets after the get() method to extract further items.

    You can also assign the expression my_dict.get(None) (herein, None is key name − first argument) to a variable name, and then use the returned data. The second argument is optional and its default value is None (different from key name). Since the value of respective key None is 22, therefore the returned value from the expression my_dict.get(None) is 22.

    The value of second argument will be returned only when the first argument is not present in the parent dictionary literal. You should not avoid the second argument, and place some descriptive literal (boolean / int / string) to distinguish it from the first argument. Returning False or 0 as second argument from the get() method in some cases, is very useful.

update()

    The update() method always takes one argument of dictionary data-type. You may individually add/modify some items as shown in below example 2, but with update() method, you can easily add/modify multiple items in a parent dictionary literal or variable name. When any key is not present in the parent dictionary literal, then the item is added to a new key with that name, after all other items (see Example 3).

Example 2

my_dict = {'': 'abc', None: 22, 'key': ['def', 'ghi']}
my_dict[''] = 'xyz'
my_dict[None] = 3.14
print( my_dict )   # Outputs {'': 'xyz', None: 3.14, 'key': ['def', 'ghi']}

Example 3

my_dict = {'': 'abc', None: 22, 'key': ['def', 'ghi']}
my_dict.update({'': 'xyz', None: 3.14, 0: True})
print( my_dict )   # Outputs {'': 'xyz', None: 3.14, 'key': ['def', 'ghi'], 0: True}


pop(), popitem()

    D.pop(k[,d]) in Help Documen­tation, means Dictionary_literal.pop( key[, default] ) − that is, key name specified inside the parentheses will be removed, and corres­ponding value of that key name is returned to a variable name. The original dictionary literal will be modified after this operation. When the specified key is not found in the dictionary literal, then the second argument (default value) if mentioned, will be returned. When the second argument is not specified in the pop() method, then KeyError will be shown in the Command Line Console or VSCode Editor Terminal.

my_dict = {'': 'abc', None: 22, 'key': ['def', 'ghi']}

my_item = my_dict.pop('key')
print( my_dict, type( my_dict ) )
print( my_item, type( my_item ) )

new_item = my_dict.pop('abc', 'Not Found')
print( my_dict, type( my_dict ) )
print( new_item, type( new_item ) )

{'': 'abc', None: 22} <class 'dict'>
['def', 'ghi'] <class 'list'>
{'': 'abc', None: 22} <class 'dict'>
Not Found <class 'str'>

    popitem() method takes no argument, and removes the last item and returns it in a (key, value) pair, as pop() method does for other data-types. The (key, value) pair is of tuple data-type, that is key is the first element of the returned tuple, and the respective value will be the second element of that (returned) tuple. You should not confuse these when any key name is of tuple data-type or its value is of tuple/list/dictionary data-type. As in the following example also, the value of last item is a list data-type, and therefore, the second element of returned tuple from popitem() method will be a NESTED list. If the parent dictionary literal is an empty dictionary, then popitem() method will raise KeyError.

my_dict = {'': 'abc', None: 22, 'key': ['def', 'ghi']}

my_item = my_dict.popitem()
print( my_dict, type( my_dict ) )
print( my_item, type( my_item ) )

{'': 'abc', None: 22} <class 'dict'>
('key', ['def', 'ghi']) <class 'tuple'>

copy(), clear()

    Since a dictionary literal is a mutable data-type, the clear() method does not take any argument, and removes all items from the dictionary literal, and the original (parent) dictionary literal will become an empty dictionary. Similarly, the copy() method does not take any argument, and it copies the items (in key:value pair) to another variable name. This can also be done by assignment operator.

my_dict = {'': 'abc', None: 22, 'key': ['def', 'ghi']}

new_dict = my_dict.copy()
print( my_dict )
print( new_dict )
empty_dict = my_dict.clear()
print( empty_dict )   # Outputs None
print( my_dict )   # Outputs {}

{'': 'abc', None: 22, 'key': ['def', 'ghi']}
{'': 'abc', None: 22, 'key': ['def', 'ghi']}
None
{}

setdefault(self, key, default=None, /)

    When any new key and default value is provided inside parentheses of setdefault() method, then they are added to the dictionary literal in key:value pair. When the second argument is not provided, then the default value is None for respective key added to the dictionary literal. However, when any key name is already present in the dictionary literal, then that key:value pair will not be changed. This method can be useful, when default values for some key names are added to a dictionary literal (for example, a person's profile), which can be modified later.

my_dict = {'': 'abc', None: 22, 'key': ['def', 'ghi']}

value1 = my_dict.setdefault('address', "Not Available")   # New key added to above dictionary.
print(my_dict, value1)

value2 = my_dict.setdefault( 'middle_name' )   # Default value is None here.
print(my_dict, value2)

value3 = my_dict.setdefault('key', "Will not be modified")   # There is no effect on the dictionary literal.
print(my_dict, value3)

{'': 'abc', None: 22, 'key': ['def', 'ghi'], 'address': 'Not Available'} Not Available
{'': 'abc', None: 22, 'key': ['def', 'ghi'], 'address': 'Not Available', 'middle_name': None} None
{'': 'abc', None: 22, 'key': ['def', 'ghi'], 'address': 'Not Available', 'middle_name': None} ['def', 'ghi']

fromkeys(iterable, value=None)

    You can create a new dictionary, with specified keys as a list/tuple data-type, as the first argument inside the fromkeys() method. When the second argument is not provided, the value of respective items will be None.

new_sequence = (1, 2, 3, 4, 5)
new_dict = dict.fromkeys(new_sequence)
print( new_dict, type( new_dict ) )

my_dict = dict.fromkeys(new_sequence, 'Will be added later')
print( my_dict, type( my_dict ) )

{1: None, 2: None, 3: None, 4: None, 5: None} <class 'dict'>
{1: 'Will be added later', 2: 'Will be added later', 3: 'Will be added later', 4: 'Will be added later', 5: 'Will be added later'} <class 'dict'>

items(), keys(), values()

my_dict = {'': 'abc', None: 22, 'key': ['def', 'ghi']}
print( my_dict.items(), type( my_dict.items() ) )
print( my_dict.keys(), type( my_dict.keys() ) )
print( my_dict.values(), type( my_dict.values() ) )

dict_items([('', 'abc'), (None, 22), ('key', ['def', 'ghi'])]) <class 'dict_items'>
dict_keys(['', None, 'key']) <class 'dict_keys'>
dict_values(['abc', 22, ['def', 'ghi']]) <class 'dict_values'>

    The three dictionary methods, items(), keys(), and values returns special sequence data-types, dict_items (list of tuples), dict_keys (list of key names) and dict_values (list of items' value) respectively. You can convert them into list or tuple data-types or use them directly in for or while loops.

my_dict = {'': 'abc', None: 22, 'key': ['def', 'ghi']}
my_list = list( my_dict.items() )
key_list = list( my_dict.keys() )
values_list = list( my_dict.values() )
print( my_list, type( my_list ) )
print( key_list, type( key_list ) )
print( values_list, type( values_list ) )

[('', 'abc'), (None, 22), ('key', ['def', 'ghi'])] <class 'list'>
['', None, 'key'] <class 'list'>
['abc', 22, ['def', 'ghi']] <class 'list'>

my_dict = {'': 'abc', None: 22, 'key': ['def', 'ghi']}
for key, value in my_dict.items():
    print( f"Key is {key} and its value is {value}." )   # Indentation is important here.

Key is   and its value is abc.
Key is None and its value is 22.
Key is key and its value is ['def', 'ghi'].

Check whether any key exists in the Dictionary Literal

my_dict = {'': 'abc', None: 22, 'key': ['def', 'ghi']}

my_key = 'key'
if my_key in my_dict:
    print( f"Key {my_key} is present and its value is {my_dict[my_key]}." )   #

new_key = 'abc'
if new_key not in my_dict:
    print( f"Key {new_key} is not present." )   #
    print( f"{my_dict[new_key]}" )   # Extracting its value will throw ERROR.

Key key is present and its value is ['def', 'ghi'].
Key abc is not present.
Traceback (most recent call last):
  File "C:\xampp\htdocs\python2023\new.py", line 10, in <module>
    print( f"{my_dict[new_key]}" )   # Extracting its value will throw ERROR.
              ~~~~~~~^^^^^^^^^
KeyError: 'abc'

    You can also find (search) any character or item/element in a sequence data-type, such as string, list, tuple or dictionary, as described in above example, using in or not in keywords, and if block of codes.

method nameReturned TypeDescription
get()data-type of item, or DefaultIf you don't provide the second argument in get() method, None will be returned.
update()Noneupdate() method never returns anything, that is you don't have to assign the expression to a variable name. The original dictionary literal will be modified after update() method is correctly applied!
pop()data-type of item, or second argumentWhen the second argument is not specified in the pop() method, then KeyError is shown.
popitem()tupleRemoves the last item and returns key:value pair as items in a tuple literal.
copy()dictSame dictionary literal is assigned to another variable name
clear()dictThe original dictionary literal will become an empty dictionary.
items()dict_itemsSpecial data-type
keys()dict_keysSpecial data-type
values()dict_valuesSpecial data-type
fromkeys()dictNew dictionary literal will be created from list/tuple sequence data-type.
setdefault()dictWhen you attempt to add a new key, this method will be helpful.


Leave a Comment: