(Python) Dictionaries or associative arrays


Dictionary

Let's take a look at another Python composite data type, called dictionary, which is similar to a list in that it is a collection of objects.
Dictionaries and lists have the following characteristics:
  • both are mutable;
  • both are dynamic (can grow and shrink as needed);
  • both can be nested (a list can contain another list, a dictionary can contain another dictionary, a dictionary can also contain a list, and vice versa).
Dictionaries differ from lists primarily in how elements are accessed:
  • list elements are accessed by their position in the list through indexing;
  • Dictionary elements are accessed using keys.
Dictionaries are a data structure implemented in Python, better known as an associative array. A dictionary consists of a set of key pairs -value. Each key-value pair maps the key to the corresponding value.

 

Creating a dictionary
You can define a dictionary by enclosing a comma-separated list of key-value pairs in curly braces ({}). A colon (:) separates each key from its associated one values: d = { <key>: <value>, <key>: <value>, . . . <key>: <value> }
You can create a dictionary with the built-in dict() function. The dict()  argument must be a sequence of key-value pairs. A list of tuples works well for this: d = dict([ (<key>, <value>), (<key>, <value), . . . (<key>, <value>) ]) You can display the contents of the list on the screen simply with the print() command. Entries in the dictionary are displayed in the order in which they were created.

Access dictionary elements


To work with the elements of a dictionary, they must be accessible somehow. If you can't get them by index, how can you get them?
The value is retrieved from the dictionary by specifying the corresponding key in square brackets ([]).

For example, displaying the capital of Abkhazia from the dictionary created in the previous task: print(dict_country['Abkhazia'])
If you refer to a key that is not in the dictionary, Python throws an exception: print(dict_country['Russia']) Traceback (most recent call last ): File "<...>", line ..., in <module>
    print(dict_country[& #39;Russia'])
KeyError: 'Russia' ;

 
Adding elements to the dictionary
Adding an entry to an existing dictionary is as simple as assigning a new key and value: dict_country['Russia'] = 'Moscow'  
Updating a dictionary entry
If you want to update an entry, you can simply assign a new value to an existing key: dict_country['Russia'] = 'Moscow'  
Remove entry from dictionary
To delete an entry, use the del operator, specifying the key to delete: del dict_country[<key>]
While accessing elements in a dictionary is order independent, Python ensures that the order of elements in a dictionary is preserved. When displayed, the elements will be displayed in the order in which they were defined, and the keys will also be repeated in that order. Items added to the dictionary are added at the end. If elements are removed, the order of the remaining elements is preserved.

It should be remembered that the keys of the dictionary, as well as the elements of the dictionary, can be of different types. A dictionary can also have the following content: d = {42: [2, 3, 6, 7], 2.78: 'bbb', True: 1} print(d[42][1]) # 3 - to access nested elements, use an additional key or index

Built-in Dictionary Methods

Some of the methods you learned about strings, lists, and tuples also work with dictionaries. For example, the in (or not in) method allows you to determine if a particular key exists. in the dictionary.

And also allows you to go through all the keys of the dictionary. for key in dict_country: print(key) You can also iterate over key-value pairs using the items() method. for key, value in dict_country.items(): print(key, value) Other commonly used methods are listed in the table.
  The The The The
Name Method Description (example)
dictionary size len() returns the number of elements in the dictionary 
len(dict_country)
updating dictionary update() allows you to update several dictionary pairs at once
dict_country.update({'Russia': 'Moscow', 'Armenia': 'Yerevan'})< /pre>
get value by key get() allows you to get the value by the specified key. Can be used to check if a particular key exists in a dictionary
dict_country.get('Russia') # returns value by key,
                              # if there is no such key, it will return None
dict_country.get('Russa', 0) # if there is no Russia key, it will return 0
                                # (instead of 0, you can set any value
remove key pop() pop() method removes a key and returns its corresponding value.
dict_country.pop('Bahamas')
dictionary keys  keys() keys() method returns a collection of keys in a dictionary.
dict_country.keys()
dictionary values values()Method values() returns a collection of values ​​in a dictionary.
dict_country.values()
dictionary pairs items() items() method returns a collection of values ​​in a dictionary.
dict_country.items()