Python dictionaries are mappings that 'map' a 'key' to a 'value'. There are different ways of creating a dictionary in Python as shown below:
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
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:
a['thirteen']=13
print a
The length of the dictionary can be obtained using 'len':
print len(a)
We can check if some key exists in a dictionary as follows:
print 'thirteen' in a
print 'thirteen' not in b
d[key] returns the value associated with the key:
print a['one']
If a key doesn't exist in the dictionary, a KeyError is generated:
print a['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.
print a.get('thirteen',None)
print a.get('fourteen',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.
print a.keys()
print a.values()
print a.items()
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.
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': '----.'
}
print morse
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)