You are on page 1of 8

5/10/2020 Dictionary_Week4

Learning Outcomes:
What is a dictionary
How it is created
How to add, remove, and change elements of a dictionary

Why we need dictionary? ¶


protein sequence names and their sequences
Transcription factor binding proteins and their binding sites
DNA restriction enzyme names and their motifs
codons and their associated amino acid residues
gene names and their co-ordinates

Properties of dictionaries:
curly brackets are used for dictionaries in Python
elements are key-value pairs
unordered container
elements are indexed using keys
mutable container
can contain elements of a different data type

Ways to create dictionaries

1) Empty dictionary

In [ ]: '''The syntax for creating a dictionary is similar to that for creating a lis
t,
but we use curly brackets rather than square ones.'''

a = {} # empty dctionary
a

In [ ]: # Creating empty dictionary using dict constructor


dict()

localhost:8888/nbconvert/html/Dictionary_Week4.ipynb?download=false 1/8
5/10/2020 Dictionary_Week4

2) Create dictionary with elements

In [ ]: '''Each pair of data, consisting of a key and a value, is called an item or el


ement.
When storing items in a dictionary, we separate them with commas. Within an in
dividual item,
we separate the key and the value with a colon. '''

# output that the nucleotides and their counts are stored together
# in the a variable:

a = {'A':3, 'G':0, 'C':5, 'T':1} # dictionary with elements


a

In [ ]: # Splitting the dictionary definition over several lines makes it easier to re


ad and
# doesn't affect how the code works

gencode = {
'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',
'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K',
'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L',
'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q',
'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V',
'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E',
'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S',
'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_',
'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W'}
gencode

In [ ]: # Using keyword arguments in dict constructor; Note no quotes around variable


names
dict(A = 3, G = 5)

In [ ]: # using iterables: list of tuples


tmp_list = [('A', 3), ('G', 5)]
dict(tmp_list)

In [ ]: # using iterables: nested tuples


tmp = (('A', 3), ('GG', 5))
dict(tmp)

localhost:8888/nbconvert/html/Dictionary_Week4.ipynb?download=false 2/8
5/10/2020 Dictionary_Week4

In [ ]: # using iterables: nested list


tmp_list = [['A', 3], ['G', 5]]
dict(tmp_list)

3) Creating a Dictionary from multiple keys and initializing all with the same
value

Syntax: dict.fromkeys(keys, value)

keys: Required. An iterable specifying the keys of the new dictionary


value: Optional. The value for all keys. Default value is None

In [ ]: a=dict.fromkeys(['A','T','C']) # using list as keys and default value


a

In [ ]: b=dict.fromkeys(['A','T','C'], 0) #changing default value


b

In [ ]: b=dict.fromkeys(('A','T','C'), 0) # using tuple as keys


b

In [ ]: b=dict.fromkeys('ATC', 0) # using string as keys


b

Accessing elements of a dictionary

1) Accessing single elements

In [42]: # By passing keys inside square brackets


a = {'A':3, 'G':0, 'C':5, 'T':1} # dictionary with elements
a['A']

Out[42]: 3

In [44]: # if key is not present, we will get an error


a = {'A':3, 'G':0, 'C':5, 'T':1} # dictionary with elements
if 'U' in a:
a['U']

localhost:8888/nbconvert/html/Dictionary_Week4.ipynb?download=false 3/8
5/10/2020 Dictionary_Week4

In [45]: # by get method


a = {'A':3, 'G':0, 'C':5, 'T':1} # dictionary with elements
print ("The value of A is = ", a.get('A'))
print ("The value of U is = ", a.get('U'))

The value of A is = 3
The value of U is = None

In [46]: a = {'A':3, 'G':0, 'C':5, 'T':1} # dictionary with elements


print ("The value of U is = ", a.get('U', 0))

The value of U is = 0

In [47]: a = {'A':3, 'G':0, 'C':5, 'T':1} # dictionary with elements


print ("The value of U is = ", a.get('U', []))

The value of U is = []

2) Accessing all keys, values, and items

In [48]: # you can also use keys() method to get all keys in a dictionary
a = {'A':3, 'G':0, 'C':5, 'T':1}
a.keys()

Out[48]: dict_keys(['A', 'G', 'C', 'T'])

In [49]: # you can also use values() method to get all values in a dictionary
a = {'A':3, 'G':0, 'C':5, 'T':1}
a.values()

Out[49]: dict_values([3, 0, 5, 1])

In [50]: # you can also use items() method to get all keys-value pairs
a = {'A':3, 'G':0, 'C':5, 'T':1}
a.items()

Out[50]: dict_items([('A', 3), ('G', 0), ('C', 5), ('T', 1)])

Loop through a dictionary


we can loop through a dictionary using a for loop

In [ ]: # to print keys one by one.


a = {'A':3, 'G':0, 'C':5, 'T':1}
for k in a:
print (k)

localhost:8888/nbconvert/html/Dictionary_Week4.ipynb?download=false 4/8
5/10/2020 Dictionary_Week4

In [ ]: # we can print keys and values as well with slight modification in above loop
a = {'A':3, 'G':0, 'C':5, 'T':1}
for k in a:
print (k, a[k])

In [ ]: # items() method returns key and value pair as tuple


a = {'A':3, 'G':0, 'C':5, 'T':1}
for k, v in a.items():
print (k, v)

In [ ]: # we can loop through values


a = {'A':3, 'G':0, 'C':5, 'T':1}
for k in a.values():
print (k)

Adding elements

We can use assignment statement to add new element to dictionary.


In assignment, new key will be used as index and a value will be assigned to that element.

In [ ]: dna = {}
dna['A'] = 1 # this procedure adds a single element at a time
dna

To add one or more than one elements we can use update method

In [ ]: dna = {}
dna.update({'A':1})
print ("dna after adding a single element = ", dna)

dna.update({'G':3, 'T':5})
print ("dna after adding more than one elements = ", dna)

# note each step updates dna dictionary

We can add both mutable and immutable elements as


values in dictionary

localhost:8888/nbconvert/html/Dictionary_Week4.ipynb?download=false 5/8
5/10/2020 Dictionary_Week4

In [ ]: a = {}
a['one'] = 1
a['two'] = 3.0
a['three'] = []
a['four'] = ()
a['five'] = "ATGC"
a['six'] = []
a

# Note we can store duplicate values in dictionary with different key names
# Here we have two keys six and three containing empty list

Changing elements in dictionary

Each key can occur only once. Dictionary holds unique elements only

In [ ]: a = {'five': 'ATGC', 'four': (), 'one': 1, 'three': [], 'two': 3.0}


a['four'] = 5
a

# Note: new value will replace old item

In [ ]: # we can change more than one elements at a time using update

a = {'five': 'ATGC', 'four': (), 'one': 1, 'three': [], 'two': 3.0}


a.update({'five':[], 'four':{}, 'one':(), 'two':set()})
a

Only immutable elements can be used as keys


In [ ]: a = {}
a[(2,3)] = ''
print ('Adding tuple as a key = ', a)

a['test'] = ''
print ('Adding string as a key = ', a)

a[[4,5]] = ''
print ('Adding list as a key = ', a)

# Note: if we execute this code, we can see tuples and strings are added succe
ssfully.
# However, list can't be used as a key

Remove elements from dictionary


localhost:8888/nbconvert/html/Dictionary_Week4.ipynb?download=false 6/8
5/10/2020 Dictionary_Week4

1) del method
The del statement removes a key-value pair from the dictionary. It’s similar to del in list except that it
accepts key not index.

In [ ]: dna = {'A':5, 'T':3, 'C': 1, 'G':0}


del dna['A']
dna

In [ ]: dna = {'A':5, 'T':3, 'C': 1, 'G':0}


del dna['U']
dna

#Note: we will get key error if that key is not present in the dictionary

In [ ]: dna = {'A':5, 'T':3, 'C': 1, 'G':0}


if 'U' in dna:
del dna['U']
dna

# We can use membership testing to avoid error in case if key is not present

In [ ]: dna = {'A':5, 'T':3, 'C': 1, 'G':0}


del dna
dna

# The del keyword can also delete the dictionary completely if only dictionary
name is used

2) clear() method
removes all elements from the dictionary.

In [ ]: dna = {'A':5, 'T':3, 'C': 1, 'G':0}


dna.clear()
dna

# We will get an empty dictionary after applying clear method

3) pop(key) method
removes the item with the specified key name
we will get the value of the deleted key

In [ ]: dna = {'A':5, 'T':3, 'C': 1, 'G':0}


dna.pop('A')

localhost:8888/nbconvert/html/Dictionary_Week4.ipynb?download=false 7/8
5/10/2020 Dictionary_Week4

In [ ]: # it will raise an error if the key is not specified


dna = {'A':5, 'T':3, 'C': 1, 'G':0}
dna.pop()

In [ ]: # it will also raise an error if the key is not present in the dictionary
dna = {'A':5, 'T':3, 'C': 1, 'G':0}
dna.pop('a')

4) popitem() method
removes the last element that was inserted in the dictionary

In [ ]: a = {}
a['one'] = 1
a['two'] = 3.0
a['three'] = []
a['four'] = ()
a['five'] = "ATGC"
a['six'] = []

print ('The remove item is = ', a.popitem())

# Note: six was the last element that was inserted in the dictionary. It is re
moved.

Finding numbers of elements in dictionary


In [ ]: dna = {'A':5, 'T':3, 'C': 1, 'G':0}
len(dna)

Making a shallow copy of dictionary


In [ ]: a = {'A':5, 'T':3, 'C': 1, 'G':0}
b = a
c = a.copy()

del a['A']

print ('a = ', a)


print ('b = ', b)
print ('c = ', c)

localhost:8888/nbconvert/html/Dictionary_Week4.ipynb?download=false 8/8

You might also like