Python Programming
Topics:

Dictionary

It is an non-sequential, unordered, redundant and mutable collection as key:value pairs. Keys are always unique but values need not be unique.

Unlike a list, dictionary is not a sequence.

List vs Dictionary

    0  1  2 3 4 5

list = [1,'A',2,3,2,8.7]

dict = {0:1,1:'A',2:2,3:3,4:2,5:8.7}

List has numeric index only in sequential order starting from zero.

Dictionary is has keys instead of index which can be numeric, string or tuple. They are unordered but they are always unique.

0 1 2 3 4 # indexes are not there
{'A':'A','Apple':253,12:3,13:435,445:34}

Properties of dictionary

  1. Unordered key:value pair collection
  2. Unique and non-mutable keys
  3. No restriction on values
  4. Not a sequence
  5. Mutable like a list

Built-in functions for a dictionary object: dir(dict)

CREATE : 'setdefault', 'fromkeys', 'copy'

READ : 'get', 'items', 'keys', 'values'

UPDATE : 'update'

DELETE : 'clear','pop', 'popitem'

setdefault(key,value) : It inserts a new key value pair to dictionary.

>>> d = {}
>>> d.setdefault('a',110)
100
>>> d
{'a': 100}

fromkeys() : It gets the keys for a dictionary from a list/tuple.
Values by default is None or same for all the keys when given.

>>> l = [1,2,5,3]
>>> {}.fromkeys(l)
{1: None, 2: None, 3: None, 5: None}
>>> {}.fromkeys(l,1000)
{1: 1000, 2: 1000, 3: 1000, 5: 1000}

get(key,alt.value): It returns the value for a given key or None or alternate value if given.

>>> d = {1:100,2:200,3:00}
>>> d.get(2)
200
>>> d.get(4,'Not found')
Not found

keys() : It returns iterable sequence of keys without sequence.

>>> d = {1:100,2:200,3:00}
>>> d.keys()
dict_keys([1,3,2])

values() : It returns iterable sequence of values without sequence.

>>> d = {1:100,2:200,3:00}
>>> d.keys()
dict_valuess([200,100,300])

items(): It returns iterable sequence of key:value pairs without sequence.

>>> d = {1: 10, 2: 34, 3: 56, 4: 90}
>>> d.items()
dict_items([(1, 10), (2, 34), (3, 56), (4, 90)])

>>> for i in d: print(i)
...
1
2
3
4

>>> for i in d.keys(): print(i)
...
1
2
3
4

>>> for i in d.values(): print(i)
...
10
34
56
90

>>> for i in d.items(): print(i)
...
(1, 10)
(2, 34)
(3, 56)
(4, 90)

>>> for i in d.items(): print(i[0])
...
1
2
3
4
>>> for i in d.items(): print(i[1])
...
10
34
56
90

>>> for k,v in d.items(): print(k,v)
...
1 10
2 34
3 56
4 90

update() : updates the value for a given key.

>>> d
{1: 10, 2: 34, 3: 56, 4: 90}
>>> d.update({2:35})
>>> d
{1: 10, 2: 35, 3: 56, 4: 90}
#### If you update a non existing key:value pair then it gets inserted.
>>> d.update({5:35})
>>> d
{1: 10, 2: 35, 3: 56, 4: 90, 5: 35}

pop(key): It pops the value for a given key.

>>> d
{1: 10, 2: 35, 3: 56, 4: 90, 5: 35}
>>> d.pop(3)
56
>>> d
{1: 10, 2: 35, 4: 90, 5: 35}

popitem(): delets a random key value pair.

>>> d
{1: 10, 2: 35, 4: 90, 5: 35}
>>> d.popitem()
(1, 10)

clear() : It delets all key:value pairs.

>>> d.clear()
>>> d
{}

copy() : It creates a shallow/seperate copy for the object.

>>> d = {1:100,2:200,3:300}
>>> a = d
>>> b = d.copy()
>>>
>>> d
{1: 100, 2: 200, 3: 300}
>>> a
{1: 100, 2: 200, 3: 300}
>>> b
{1: 100, 2: 200, 3: 300}
>>>
>>> d.popitem()
(1, 100)
>>> d
{2: 200, 3: 300}
>>> a
{2: 200, 3: 300}
>>> b
{1: 100, 2: 200, 3: 300}

dict comprehension

It is creating a new dict object from an existing dict object in one line.

Syntax:

a) {key_exp:value_exp for key,value in dict_object}
d) {key_exp:value_exp for key,value in dict_object if cond}

>>> l = [1,2,3,4,5]
>>> [i**2 for i in l]
[1, 4, 9, 16, 25]
>>>
>>> d = {1:10,2:20,3:30}
>>> {k:v for k,v in d.items()}
{1: 10, 2: 20, 3: 30}
>>>
>>> {k**3:v**2 for k,v in d.items()}
{8: 400, 1: 100, 27: 900}
>>>
# Swapping the key:value pair of a dictionary
>>> {v:k for k,v in d.items()}
{10: 1, 20: 2, 30: 3}
>>> d = {1:100,2:200,3:300}
>>> {i**2:j for i,j in d.items()}
{1: 100, 4: 200, 9: 300}
>>> {i:j for i,j in d.items()}
{1: 100, 2: 200, 3: 300}
>>> {j:i for i,j in d.items()}
{200: 2, 300: 3, 100: 1}

Q1: Write a program to print sorted dictionary keys.

In [3]:
def function(d):
    return sorted(d.keys())

result = function({1:'a',3:'b',2:'c',20:'d',10:'e'})
print(result)
[1, 2, 3, 10, 20]

Q2: Write a program to reverse key:value pairs in a dictionary.

In [4]:
def function(d):
    return {v:k for k,v in d.items()}

result = function({1:'a',3:'b',2:'c',20:'d',10:'e'})
print(result)
{'e': 10, 'd': 20, 'c': 2, 'b': 3, 'a': 1}

Q3. Write a program to find the value for any given key in a dictionary. Return 'not a valid key' if key is not present.

In [6]:
def function(d,key):
    return d.get(key,'not a valid key')

result1 = function({1:'a',3:'b',2:'c',20:'d',10:'e'},1)
print(result1)

result2 = function({1:'a',3:'b',2:'c',20:'d',10:'e'},101)
print(result2)
a
not a valid key

Q4: Write a program to covert all keys in a dictionary to upper case and all values to lowercase.

In [9]:
def function(d):
    return {str(k).upper():str(k).lower() for k,v in d.items()}

result = function({'apple':'a',2:'b',2:'c','d':123})
print(result)
{'2': '2', 'D': 'd', 'APPLE': 'apple'}

Q5: In gene expression, mRNA is transcribed from a DNA template. The 4 nucleotide bases of A, T, C, G corresponds to the U, A, G, C bases of the mRNA. Write a program that returns the mRNA transcript given the sequence of a DNA strand.

In [13]:
def function(dna):
    d = {'A':'U','T':'A','C':'G','G':'C'}
    rna = ""
    for i in dna:
        rna += d.get(i)
    return rna

result = function("ATTCGATCCCGCTACGAT")
print(result)
UAAGCUAGGGCGAUGCUA

Q6: Write a program to count letters in word and represent them as a dictionary.

In [14]:
def function(word):
    return {i:word.count(i) for i in word}

result = function("ATTCGATCCCGCTACGAT")
print(result)
{'G': 3, 'A': 4, 'T': 5, 'C': 6}

Q7. Write a program to associate a given list of keys with corresponding list of values.

In [15]:
def function(keys,values):
    return dict(zip(keys,values))

result = function(['A','D','B','C'],[1,4,2,3])
print(result)
{'B': 2, 'A': 1, 'D': 4, 'C': 3}

Set

  • set : mutable collection of dict keys

Properties:

  • unordered/unsorted and non-sequential
  • not sequential indexes
  • uniques values (It does not support redundancy)
  • mutable

Empty set is represented with 'set()'

s = set()

set() to remove duplicates form a list

l = [1,2,3,2,3,1]
ist(set(l))
[1, 2, 3]

Important operations on a set

  • difference(): it is a non-commutative property, i.e, a-b != b-a. It find the unique items is first set compared to the second set.

    s = {1,3,4} t = {1,2,5} s-t {3, 4} t-s {2, 5}

  • symmetric_difference(): sum of difference from both sides. Non-mutual data set with no duplicate.

    s = {1,3,4} t = {1,2,5} s-t {3, 4} t-s {2, 5} s.symmetric_difference(t) {2, 3, 4, 5} s^t {2, 3, 4, 5}

  • intersection() : It finds mutual data sets by doing and/intersection.

    s {1, 3, 4} t {1, 2, 5} s.intersection(t) {1} t.intersection(s) {1} s&t {1} t&s {1}

  • union() : It joins the data sets with only one occurance of duplicate. It is like 'or' operation.

    s {1, 3, 4} t {1, 2, 5} s.union(t) {1, 2, 3, 4, 5} t.union(s) {1, 2, 3, 4, 5} t|s {1, 2, 3, 4, 5} s|t {1, 2, 3, 4, 5}

  • issuperset() : it is booelan opearation for finding if the given data set contains all elements from the other data set.

    a = {1,2,3,4,5} b = {1,2,7} c = {3,4} a.issuperset(b) False a.issuperset(c) True

  • issubset() : it is booelan opearation for finding if all the items is the given data set exists in some other data set.

    a = {1,2,3,4,5} b = {1,2,7} c = {3,4} a.issubset(b) False c.issubset(a) True

  • isdisjoint() : It means mutually exclusive. Two sets are disjoint when they have nothing in common.

    a = {1,2,3,4,5} b = {1,2,7} c = {3,4} d = {6} a.isdisjoint(b) False a.isdisjoint(c) False a.isdisjoint(d) True

Other set attributes

  • s.add() : adds a new value to the set

    s = {1,2,3} s.add(4) s {1,3,2,4}

  • pop() :pops a random value from the set like dict.popitem()\

    s {1, 2, 3, 4, 5, 7, 9} s.pop() 1

  • discard() : deletes a value from the set if present, returns None if not

    s {3, 4, 5, 7, 9} s.discard(7) s {3, 4, 5, 9} s.discard(7)

  • remove() : deletes a value from the set if present, returns KeyError if not

    s {3, 4, 5, 9} s.remove(4) s {3, 5, 9}