There are several ways you can create a python dictionary either empty or having some initial key:value pairs.Let us understand every method one by one with sample code.
1.An empty dictionary – To create an empty dictionary there are two ways either using {} or dict() constructor.
People often get confused between set and dictionary creation using {}. The main difference is that you can create empty dictionary using {} but not empty set.
A set created using {} should contain atleast one value.
>>> dict1 = {}
>>> type(dict1)
<class 'dict'>
>>> dict1 = dict()
>>> type(dict1)
<class 'dict'>
2.Using literals for keys – Keys is unique and hashable .So int,string,char etc can be used as key . Also ,there can be keys of different datatype in same dictionary.
>>> count= {1:'one',2:'two',3:'three',4:'four'}
>>> print(count)
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
3.Passing key-value as default argument in dictionary constructor.
count = dict(1 = one,2 = two,3 = three,4 = four)
print(count)
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
4.Using list of tuples – Each tuple in the list represent the key:value pair .
>>> iterable = [(1,one),(2,two),(3,three),(4,four)]
>>> count = dict(iterable)
>>> print(count)
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
5.Using list of keys mapped to a default value – This is a very useful way to create a dictionary when you know all the keys already. A default value is set to all the key using this method.
>>> subjects = ['English','Hindi','Mathematics','Science']
>>> grades = dict.fromkeys(subjects,0)
>>> print(grades)
{'English': 0, 'Hindi': 0, 'Mathematics': 0, 'Science': 0}