Python Dictionaries

Python Dictionaries


Another useful data type python dictionaries built into Python is (see Mapping Type - Tyrant). Dictionaries are seldom found in other languages as "associative memories" or "associative arrays". Unlike sequences, which are indexed by a series of numbers, python dictionaries are indexed by keys, which can be of any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; If a tuple contains any variable directly or indirectly, it cannot be used as a key. You cannot use lists as keys because lists can be modified using methods such as index assignment, slice assignment, or append (and) and ().

It is best to interpret a word as a set of keys: value pairs, with the requirement that the keys are unique (within a dictionary). A pair of braces form an empty dictionary: {}. Keeping a comma-separated list of keys: value pairs within braces add initial keys: value pairs to the dictionary; These are also methods written on the output.

Key operations on a dictionary are storing a value with some key and extracting the value assigned to the key. It is also possible to delete a key: value pair with Dell. If you save using a key that is then in use, the old value associated with that key is forgotten. Removing values using non-existent keys is an error.

Python Dictionaries

The display of list (D) in the dictionary returns a list of all the keys used in the dictionary order, if you want the entry in order, use only sort (D) instead. To check if the dictionary has the same key, use in the keyword.

Here is a small example using a dictionary:

>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'jack': 4098, 'sape': 4139, 'guido': 4127}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'jack': 4098, 'guido': 4127, 'irv': 4127}
>>> list(tel)
['jack', 'guido', 'irv']
>>> sorted(tel)
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False

dict() constructor creates python dictionaries directly from sequences of key-value pairs:

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'guido': 4127, 'jack': 4098}

In addition, the dict understanding can be used to construct python dictionaries from arbitrary key and value expressions:

>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
When keys are simple strings, sometimes it is easy to specify pairs using keyword arguments:


>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'guido': 4127, 'jack': 4098}


Python Dictionaries Python Dictionaries Reviewed by Sk Jha on October 14, 2019 Rating: 5

No comments:

Powered by Blogger.