Python Dictionaries

Python dictionaries are mappings that 'map' a 'key' to a 'value'. There are different ways of creating a dictionary in Python as shown below:

In [2]:
a = dict(one=1, two=2, three=3)
b = {'one': 1, 'two': 2, 'three': 3}
c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
d = dict([('two', 2), ('one', 1), ('three', 3)])
e = dict({'three': 3, 'one': 1, 'two': 2})
a == b == c == d == e
Out[2]:
True

The above dictionary(ies) map each word (key) to its corresponding number (value). We can add a key,value pair to an existing dictionary as follows:

We can add a key,value pair to an existing dictionary as follows:

In [5]:
a['thirteen']=13
In [6]:
print a
{'thirteen': 13, 'three': 3, 'two': 2, 'one': 1}

The length of the dictionary can be obtained using 'len':

In [7]:
print len(a)
4

We can check if some key exists in a dictionary as follows:

In [10]:
print 'thirteen' in a
True

In [11]:
print 'thirteen' not in b
True

d[key] returns the value associated with the key:

In [18]:
print a['one']
1

If a key doesn't exist in the dictionary, a KeyError is generated:

In [19]:
print a['fourteen']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-19-df991e28d4f3> in <module>()
----> 1 print a['fourteen']

KeyError: 'fourteen'

We can also use the 'get' function to return the value associated with a key and an optional default if the key doesn't exist in the dictionary.

In [14]:
print a.get('thirteen',None)
13

In [15]:
print a.get('fourteen',None)
None

To get the list of all keys in the dictionary use '.keys()'. '.values()' will return a list of all values. '.items()' will return a list of all (key,value) pairs.

In [23]:
print a.keys()
print a.values()
print a.items()
['thirteen', 'three', 'two', 'one']
[13, 3, 2, 1]
[('thirteen', 13), ('three', 3), ('two', 2), ('one', 1)]

Exercise:

Below is a dictionary of morse code. Use it to make a function 'str2morse(s)' to find the morse code equivalent of any input string such that a whitespace is printed between the morse code representation of every words in the input string s. Then make another function 'morse2str(m)' which returns the string associated with a morse code generated by str2morse.

In [24]:
morse = {'A': '.-',     'B': '-...',   'C': '-.-.', 
        'D': '-..',    'E': '.',      'F': '..-.',
        'G': '--.',    'H': '....',   'I': '..',
        'J': '.---',   'K': '-.-',    'L': '.-..',
        'M': '--',     'N': '-.',     'O': '---',
        'P': '.--.',   'Q': '--.-',   'R': '.-.',
     	'S': '...',    'T': '-',      'U': '..-',
        'V': '...-',   'W': '.--',    'X': '-..-',
        'Y': '-.--',   'Z': '--..',
        
        '0': '-----',  '1': '.----',  '2': '..---',
        '3': '...--',  '4': '....-',  '5': '.....',
        '6': '-....',  '7': '--...',  '8': '---..',
        '9': '----.' 
        }   
In [25]:
print morse
{'A': '.-', 'C': '-.-.', 'B': '-...', 'E': '.', 'D': '-..', 'G': '--.', 'F': '..-.', 'I': '..', 'H': '....', 'K': '-.-', 'J': '.---', 'M': '--', 'L': '.-..', 'O': '---', 'N': '-.', 'Q': '--.-', 'P': '.--.', 'S': '...', 'R': '.-.', 'U': '..-', 'T': '-', 'W': '.--', 'V': '...-', 'Y': '-.--', 'X': '-..-', 'Z': '--..', '1': '.----', '0': '-----', '3': '...--', '2': '..---', '5': '.....', '4': '....-', '7': '--...', '6': '-....', '9': '----.', '8': '---..'}

A solution:

In [28]:
def str2morse(s):
    return ' '.join([morse[c] for c in s.upper()])

remorse=dict(zip(morse.values(),morse.keys())) 
#Another way of creating remorse is: dict([reversed(i) for i in morse.items()])

def morse2str(m):
    return ''.join([remorse[c] for c in m.split()])

s='hello'
m=str2morse(s)
print 'morse code of',s,'is',m
print 'from morse code:',morse2str(m)
morse code of hello is .... . .-.. .-.. ---
from morse code: HELLO

(c) Dr. Fayyaz ul Amir Afsar Minhas, DCIS, PIEAS, Pakistan.