A datatype of a value is an attribute that signifies what type of data that variable holds.In Python, datatypes are objects of builtin classes so as python dictionary.
A Dictionary object is an unordered collection of key,value pair. A python dictionary is
- Unordered – The place of elements is not fixed.So, it doesn’t support indexing or slicing.
- Mutable – It does support operations like deletion and insertion of elements.
- Key – Key is any immutable data type (such as string,numbers,tuples) which maps to a corresponding value.
Keys are case sensitive i.e ‘a’ and ‘A’ are considered as two different keys.
Key are unique.
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}
You can access dictionary value mapped to a key same as you access list by passing its index in square bracket.
Ex – dict1[key] gets you value at key ‘key’ in dict1.
There are several other methods discussed below:–
1.By direct passing key in square bracket – This is the simplest and trivial way to access a key in a dictionary.It will raise an error if key is not present.
>>> count= {1:'one',2:'two',3:'three',4:'four'}
>>> print(count[1])
one
2.Using get() method – Get method takes two parameter first is the key and second is the default return value in case key isn’t found.
>>> count= {1:'one',2:'two',3:'three',4:'four'}
>>> print(count.get(2))
one
# An example of using default value
>>> print(count.get(5,'not found'))
not found
3.Looping over all keys – To access each key in the dictionary you can use a simple for loop.
>>> count= {1:'one',2:'two',3:'three',4:'four'}
>>> for keys in count:
print(keys,'---->',count[keys])
1 ----> one
2 ----> two
3 ----> three
4 ----> four
4.Using items() method – This method returns list of tuples which contain key:value pair.
>>> count= {1:'one',2:'two',3:'three',4:'four'}
>>> print(count.items())
dict_items([(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')])
5.Using keys() method – The key method return the list of all keys present in dictionary.
>>> count= {1:'one',2:'two',3:'three',4:'four'}
>>> print(count.keys())
dict_keys([1, 2, 3, 4])
I use “for” loop and get method for accessing the keys.Mention in the comment section if you find any other method fascinating .
Python Dictionary is a mutable datatype. We can modify the dictionary after initialization.There are several ways to perform this task:-
1.By direct passing key in square bracket – This method will create a new key:value pair .If key already exist its value will be updated.
>>> count= {1:'one',2:'two',3:'three',4:'four'}
2.Using update() method – Update method takes either dictionary or an iterable of key:value pair. It add those key:value pairs which aren’t present in the dictionary.
# Adding another dictionary
>>> count= {1:'one',2:'two',3:'three',4:'four'}
>>> count2 = {5:'five',6:'six',7:'seven'}
>>> count.update(count2)
>>> print(count)
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven'}
# Update when tuple is passed
>>> count3 = [(8,'eight'),(9,'nine'),(10,'ten')]
>>> count.update(count3)
>>> print(count)
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten'}
3.setdefault() method – This method is used for insertion of new pair.It has two argument
- key – The key name to be inserted
- value(optional) – If the key is already present, this argument isn’t used else it creates a new key with value given.
Return – It return the value for the key
>>> count= {1:'one',2:'two',3:'three',4:'four'}
# Insert and return new key
>>> x = count.setdefault(5,'five')
>>> print(count)
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
# Insert a key which is already present .Hence,value parameter do nothing.
>>> x = count.setdefault(1,'no change')
>>> print(count)
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
1.Using pop(key,default ) – This method delete the specified key and return the value .
If key is not present and the defalut value is there,it is returned otherwise key error is raised.
>>> count= {1:'one',2:'two',3:'three',4:'four'}
>>> x = count.pop(4,'not found')
>>> print(x)
four
>>> print(count)
{1:'one',2:'two',3:'three'}
# Now 4 is removed
>>> x = count.pop(4,'not found')
>>> print(x)
not found
2.Using popitem() method – It removes and return the last added key:value pair as tuple or raises key error if dictionary is empty.
>>> count= {1:'one',2:'two',3:'three',4:'four'}
>>> key,val = count.popitem()
>>> print(key,'--->',value)
4 ---> four
3.clear() method – This method delete all pair in the dictionary.
>>> count= {1:'one',2:'two',3:'three',4:'four'}
>>> count.clear()
>>> print(count)
(}