About Python dictionary
In Python, a dictionary is an unordered collection of key-value pairs.
Dictionary keys must be unique and immutable, while values can be of any data type and can be mutable.
In Python, dictionary items are placed in key-value paired inside curly braces '{}' and key and value are paired with colon (:). Each key-value pair item is separated with comma (,).
Creating a dictionary in Python
Using curly braces {}:
1. Create a collection of key-value pairs ('name':'john', 'city':'Paris') and place them inside curly braces '{}'. The code will look like this: {'name':'john', 'city':'Paris'}
. A dictionary is created.
2. Create a variable my_dic
and assign the dictionary to the my_dic variable. Use print() function to print the dictionary.
Please take a closer look at the following example:
Example of creating dictionary using curly braces {}
Output of the above example
Your dictionary: {'name': 'john', 'city': 'Paris'}
Using the dict() constructor:
You can create a dictionary by passing key-value pairs as arguments, or passing an iterable (like a list or tuple whose each element has paired elements) as argument to the dict() constructor.
Dictionary from key-value pairs:
1. Create key-value pairs (name='John', age=25)
) and pass it inside dict() constructor like this - dict(name='John', age=25)
. It will create a dictionary. Please note that '=' operator is used for key-value pair.
2. Create a variable name person_dic
and assign the dictionary to the person_dic variable. Use print() function to print the dictionary as shown in the following first example.
Dictionary from list:
1. Create a list [('name', 'Jenny'), ('age', 30), ('city', 'London')]
where each element has two paired elements in a tuple e.g. ('name', 'Jenny'). Pass the list to the dict() constructor like this - dict([('name', 'Jenny'), ('age', 30), ('city', 'London')])
. It will create a dictionary.
2. Create a variable name jenny_dic
and assign the dictionary to the jenny_dic variable. Use print() function to print the dictionary as shown in the following second example.
You can create a dictionary from a tuple using dict() constructor in the same way.
Please take a closer look at the following examples:
Example of creating dictionary using dict() constructor
Output of the above example
Dictionary using dict(): {'name': 'John', 'age': 25} Dictionary from list: {'name': 'Jenny', 'age': 30, 'city': 'London'}