Python Dictionary
Python dictionary is an unordered collection of elements.
- Python Dictionary is used there are a huge amount of data because Dictionaries are optimized for retrieving data.
- Each key is used to retrieve the respective value (and not vice versa).
- key-value pairs in a dictionary are not ordered or sortable.
Create Python Dictionary
A dictionary is created using curly brackets {}
. In addition, you can directly define a dictionary with some key-value pairs.
An item has a key
and a corresponding value
that is expressed as a pair (key: value).
While the values can be of any data type and can repeat, keys must be of immutable type (string, number or tuple with immutable elements) and must be unique.
You can also create a dictionary using the built-in dict()
function.
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'Tutorial', 2: 'Reference'}
# dictionary with mixed keys
my_dict = {'name': 'Tom', 1: [2, 4, 3]}
# using dict()
my_dict = dict({1:'Tutorial', 2:'Reference'})
# from sequence having each item as a pair
my_dict = dict([(1,'Tom'), (2,'Ryan')])