Dictionaries are collection of objects which can be indexed using their keys. A dictionary contains items, which are key:value
pairs.
For one key in a dictionary, there can be only one value. Multiple keys can have same values.
A dictionary can be created using a curly bracket, {}
, or using dict()
function.
Python
# create empty dictionary
d1 = {}
print(type(d1))
<class 'dict'>
Python
# create empty dictionary
d2 = dict()
print(type(d2))
<class 'dict'>
If we have to create a dictionary with some items already present in it, we have to put the items inside the curly brackets in the form key:value
.
The keys of a dictionary must be an immutable object, such as a string or number. The values in a dictionary can be any object. A value can also be another dictionary. This way we can create nested dictionaries. The nested dictionaries can be of any depth.
Python
d1 = {'A': 3,
'B':6,
'K': {'name': 'DG'}
}
print(d1)
{'A': 3, 'B': 6, 'K': {'name': 'DG'}}
Also, we can give a list of tuples in form, (key,value) to the dict()
function. Although, I do never use this method, this is an option.
Python
d2 = dict([
('A', 3),
('B', 6),
('name', {'K': 'DG'})
])
print(d2)
{'A': 3, 'B': 6, 'name': {'K': 'DG'}}
Add items to dictionary
In real world programs, often the dictionary items get added or modified as different parts of the program run.
Following is how we add new item in a dictionary.
Python
# add new item
d1['C'] = 9
print(d1)
{'A': 3, 'B': 6, 'C': 9}
For example, while reading a FASTA file containing several sequences, we can create a dictionary with the accession number as the dictionary keys and the length of the sequence as the values.
We can even create a nested dictionary where each accession key will have a value, which is another dictionary containing the keys, such as length, sequence, name, and any other properties of the accession number.
Following is an hypothetical example.
Python
sequence_dict = {
'acc2340' : {'name': 'enolase_fragment',
'sequence' : 'AAGTCGCAT',
'length' : 8}
}
While the FASTA file is being parsed, we can create these dictionary items one by one in the program as individual sequences are read and parsed.
Modify values in a dictionary
When a value of key is a list or other mutable object, the value can be modified during the progam. For example the append()
method can be used for a list
type value in a dictionary.
This allows us to store more information in a dictionary as more results are calculated in a program.
Python
d1['D'] = [4]
print(d1['D'])
d1['D'].append(6)
print(d1['D'])
[4]
[4, 6]
Accessing the value of a key, as in d1['D']
, is call Look up
a dictioanary.
This method of getting the values using keys in a dictionary is very fast irrespective of the size of the dictionary.
Similarly, a value of a key can be reassigned.
Python
d1['D'] = 'new value'
print(d1['D'])
new value
Iterating over dictionary keys
If we need to iterate over dictionary items for retrieving and/or analyzing the data in them, we can iterate over their keys.
Python
# iterating over dictionary keys
for k in d1.keys():
print(k, d1[k])
A 3
B 6
C 9
Dictionary comprehension
Similar to list comprehension, we have the functionality of dictionary comprehension.
Python
# dictionary comprehensions
d3 = {x:x**3 for x in range(10)}
# iterate over keys to view
for k in d3:
print(k, d3[k])
0 0
1 1
2 8
3 27
4 64
5 125
6 216
7 343
8 512
9 729
Order of items in a dictionary
In newer python versions, the keys in a dictionary are ordered in same way as they are added to the dictionary.
Python
# order
d4 = {'A':4, 'H':6, 'D': 9, 'C': 3}
for k in d4:
print(k, d4[k])
A 4
H 6
D 9
C 3
We can see above that the keys are not ordered alphabetically, but in the order we have written while generating the dictionary.
Getting items of a dictionary
Items, i.e. the key:value
pairs can be fetched using items()
method.
Python
# get items
for item in d1.items():
print(item)
('A', 3)
('B', 6)
('C', 9)
('v1', 4)
('D', [4, 6])