February 22, 2020
Dictionary - Advanced Python
A dictionary is a collection which is unordered, changeable and indexed. A dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value. A dictionary is written in braces. Each key is separated from its value by a colon (:) and the items are separated by commas.
my_dict = {"name":"Max", "age":28, "city":"New York"}
Create a dictionary
Create a dictionary with braces, or with the built-in dict function.
Access items
Add and change items
Simply add or access a key and assign the value.
Delete items
Check for keys
Looping through dictionary
Copy a dictionary
Be careful when copying references.
Merge two dictionaries
Possible key types
Any immutable type, like strings or numbers can be used as a key. Also, a tuple can be used if it contains only immutable elements.
Nested dictionaries
The values can also be container types (e.g. lists, tuples, dictionaries).