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 Manipulation   in Category: Python   by amit

🕙 Posted on 2023-08-20 at 08:04:40     Read in Hindi ...


More about Dictionaries

    In previous pages, you have seen examples of some simple dictio­naries. Dictio­naries are like associ­ative arrays in other program­ming languages, such as PHP and JavaScript. A dictionary can only contain those items/elements, which have unique keys. That is, unlike string, lists, and tuples, dictio­naries are unordered collection of items, and accessing or modifying any item through index number is not guaranteed. Those items can only be accessed and also modified through their respective keys, because dictio­naries are mutable objects.

    Key names must be immutable data-type, that is, integer, float, boolean, string, tuple or None data-type, (which also should be hashable). Thus, a key name can be 0 (zero), 1 (one), etc., but those key names are not index number. An item/element in a dictionary is always in key:value pair. The key and its respective value, both are separated by the : (colon) symbol. And, the items are separated by , (comma) symbol. A empty dictionary can be created by using dict() built-in function or {} (a pair of curly braces). However, without keys items in a pair of curly braces are set data-type literal.

my_dict = { (1, 'a', None, True): 'one' }
print( my_dict, type( my_dict ) )   # Outputs as follows:

{(1, 'a', None, True): 'one'} <class 'dict'>

my_dict = { False: 'zero' }
print( my_dict, type( my_dict ) )   # Outputs as follows:

{False: 'zero'} <class 'dict'>

my_dict = { None: 'zero' }
print( my_dict, type( my_dict ) )   # Outputs as follows:

{None: 'zero'} <class 'dict'>

my_dict = { [1,2,3,4]: 'one' }
print( my_dict, type( my_dict ) )   # Outputs ERROR as follows:

Traceback (most recent call last):
  File "C:\xampp\htdocs\python2023\new.py", line 1, in <module>
    my_dict = { [1,2,3,4]: 'one' }
                    ^^^^^^^^^^^^^^^^^^^^
TypeError: unhashable type: 'list'

my_dict = { {1:'a',2:'b',3:'c'}: 'one' }
print( my_dict, type( my_dict ) )   # Outputs ERROR as follows:

Traceback (most recent call last):
  File "C:\xampp\htdocs\python2023\new.py", line 1, in <module>
    my_dict = { {1:'a',2:'b',3:'c'}: 'one' }
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: unhashable type: 'dict'

my_dict = { (1, ['a'], {}, set()): 'one' }
print( my_dict, type( my_dict ) )   # Outputs ERROR as follows:

Traceback (most recent call last):
  File "C:\xampp\htdocs\python2023\new.py", line 1, in <module>
    my_dict = { (1, ['a'], {}, set()): 'one' }
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: unhashable type: 'list'

    In the above example, you can see that even any item/element in the tuple key of a dictionary literal, is list/dictionary/set (that is, not hashable), then the same TypeError is displayed in output. Thus, every item in the tuple key also must be immutable data-type. When you remove all other items in above example, that is, ['a'], {}, set(), then (1,) key (when comma is present, it is tuple, otherwise it is int data-type) will not throw any ERROR.

    You can see in comparing different methods page, that __hash__() method is available for every data-type, however, when you check it with help() built-in function, you will find at the bottom (of help documen­tation) that __hash__ = None is specified in list, dict (dictionary), set and bytearray data-types. For other data-types, such as bool, None, int, float, complex, string, tuple, bytes, memoryview, __hash__() method is equi­valent to hash() built-in function. There are other (custom) data-types available in Python through different modules. Even you can create custom modules, classes, functions, methods and custom data-types. You should check that whether any data-type is hashable or not, by following examples:

print( help( list.__hash__ ) )

print( help( dict.__hash__ ) )

print( help( set.__hash__ ) )

print( help( bytearray.__hash__ ) )

    For above codes, the output will be same as print( help( None ) ) becuase __hash__ is equal to None (data-type) for list, dict, set, bytearray. However, the OUTPUT for following codes will be same, and they show Return hash(self).

print( help( bool.__hash__ ) )   # Outputs as follows:

print( help( int.__hash__ ) )   # Outputs as follows:

print( help( float.__hash__ ) )   # Outputs as follows:

print( help( complex.__hash__ ) )   # Outputs as follows:

print( help( str.__hash__ ) )   # Outputs as follows:

print( help( tuple.__hash__ ) )   # Outputs as follows:

print( help( bytes.__hash__ ) )   # Outputs as follows:

print( help( memoryview.__hash__ ) )   # Outputs as follows:

print( help( None.__hash__ ) )   # Outputs as follows:

Help on wrapper_descriptor:

__hash__(self, /)
    Return hash(self).

None

Adding, Modifying & Deleting an Item

    An item/element in a dictionary literal can be added, modified, or deleted using the = (assignment) operator. The process is similar to modifying/deleting any item in a list literal, except that key names are used instead of index number inside a pair of square brackets, just after the variable name or dictionary literal. Unlike list, an item in a dictionary literal can be added with the assignment operator, because dictionary is key-based sequence data-type.

my_dict = {}
my_dict['a'] = [12, 14, 16, 18]
print( my_dict )   # Outputs {'a': [12, 14, 16, 18]}

# Continued with above example:

my_dict[None] = object()
print( my_dict )   # Outputs {'a': [12, 14, 16, 18], None: <object object at 0x000002B098534270>}

    The value of an item in a dictionary literal can be of any valid data-type of Python, but you should carefully name keys. An item in a dictionary can be modified as shown below:

my_dict[None] = True
print( my_dict )   # Outputs {'a': [12, 14, 16, 18], None: True}

del my_dict[None]
print( my_dict )   # Outputs {'a': [12, 14, 16, 18]}

del my_dict
print( my_dict )   # Outputs ERROR as shown below, because whole dictionary literal is deleted

Traceback (most recent call last):
  File "C:\xampp\htdocs\python2023\new.py", line 12, in <module>
    print( my_dict )
            ^^^^^^^
NameError: name 'my_dict' is not defined

print( help( dict ) )   # Outputs as shown below:

Help on class dict in module builtins:

class dict(object)
|   dict() -> new empty dictionary
|   dict(mapping) -> new dictionary initialized from a mapping object's
|   (key, value) pairs
|   dict(iterable) -> new dictionary initialized as if via:
|       d = {}
|       for k, v in iterable:
|           d[k] = v
|   dict(**kwargs) -> new dictionary initialized with the name=value pairs
|       in the keyword argument list. For example: dict(one=1, two=2)
|
|   Methods defined here:
|
|   __contains__(self, key, /)
|       True if the dictionary has the specified key, else False.
|
|   __delitem__(self, key, /)
|       Delete self[key].
|
|   __eq__(self, value, /)
|       Return self==value.
|
|   __ge__(self, value, /)
|       Return self>=value.
|
|   __getattribute__(self, name, /)
|       Return getattr(self, name).
|
|   __getitem__(...)
|       x.__getitem__(y) <==> x[y]
|
|   __gt__(self, value, /)
|       Return self>value.
|
|   __init__(self, /, *args, **kwargs)
|       Initialize self. See help(type(self)) for accurate signature.
|
|   __ior__(self, value, /)
|       Return self|=value.
|
|   __iter__(self, /)
|       Implement iter(self).
|
|   __le__(self, value, /)
|       Return self<=value.
|
|   __len__(self, /)
|       Return len(self).
|
|   __lt__(self, value, /)
|       Return self<value.
|
|   __ne__(self, value, /)
|       Return self!=value.
|
|   __or__(self, value, /)
|       Return self|value.
|
|   __repr__(self, /)
|       Return repr(self).
|
|   __reversed__(self, /)
|       Return a reverse iterator over the dict keys.
|
|   __ror__(self, value, /)
|       Return value|self.
|
|   __setitem__(self, key, value, /)
|       Set self[key] to value.
|
|   __sizeof__(...)
|       D.__sizeof__() -> size of D in memory, in bytes
|
|   clear(...)
|       D.clear() -> None. Remove all items from D.
|
|   copy(...)
|       D.copy() -> a shallow copy of D
|
|   get(self, key, default=None, /)
|       Return the value for key if key is in the dictionary, else default.
|
|   items(...)
|       D.items() -> a set-like object providing a view on D's items
|
|   keys(...)
|       D.keys() -> a set-like object providing a view on D's keys
|
|   pop(...)
|       D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
|       If the key is not found, return the default if given; otherwise,
|       raise a KeyError.
|
|   popitem(self, /)
|       Remove and return a (key, value) pair as a 2-tuple.
|
|       Pairs are returned in LIFO (last-in, first-out) order.
|       Raises KeyError if the dict is empty.
|
|   setdefault(self, key, default=None, /)
|       Insert key with a value of default if key is not in the dictionary.
|
|       Return the value for key if key is in the dictionary, else default.
|
|   update(...)
|       D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
|       If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
|       If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
|       In either case, this is followed by: for k in F: D[k] = F[k]
|
|   values(...)
|       D.values() -> an object providing a view on D's values
|
|   ----------------------------------------------------------------------
|   Class methods defined here:
|
|   __class_getitem__(...) from builtins.type
|       See PEP 585
|
|   fromkeys(iterable, value=None, /) from builtins.type
|       Create a new dictionary with keys from iterable and values set to value.
|
|   ----------------------------------------------------------------------
|   Static methods defined here:
|
|   __new__(*args, **kwargs) from builtins.type
|       Create and return a new object. See help(type) for accurate signature.
|
|   ----------------------------------------------------------------------
|   Data and other attributes defined here:
|
|   __hash__ = None

None


Leave a Comment: