A dictionary maps from keys to values. This means it traverses the keys in order to perform specific operations on the associated values. so each key performs an operation to its respective value¶
The “in” operator is used for the keys and not for the values¶
In [1]:
# let s be the keys of the dictionary
# The histogram function counts the number of times a key appears and assigns that number as the value of that key
def histogram(s):
d = dict()
# if any of the keys in the keys provided by s is not yet in the dict, then let that key be given an initial value
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d
In [2]:
# the following code calls the histogram function and supplies the keys
histogram('Maxwell')
Inverting a dictionary¶
In [3]:
#Inverting a dictionary
def my_invers(given_dictionary):
inverted_dictionary = dict()
for key in given_dictionary:
val = given_dictionary[key]
# since the in operator is applicable to keys alone and not to values if we ask it to look up for the values in the keys it will
# definitely not find any thereby making it possible for those values to become our new keys
if val not in inverted_dictionary: # if value is not a key in the inverted dictionary
inverted_dictionary[val] = [key]
else:
inverted_dictionary[val].append(key)
return inverted_dictionary
In [4]:
my_invers(histogram('Maxwell'))
As you can see above, we have inverted the initial dictionary with its values now serving as keys¶
Python’s zip function¶
A zip is a built-in function that takes in two or more sequences and returns a list of tuples with each element appearing once in the list of tuple. That is, the tuple contains one element from each sequence¶
In [5]:
# creating a tuple of 3 elements
my_tuple = ('max', 'Go', 'come',)
In [6]:
# creating a list of 3 elements
new_myList = [100, 200, 400]
In [7]:
def myform():
new_formdic = dict()
for seq in zip(my_tuple, new_myList):# for each of the pair of items
# in the two different sequences
# the keys should come from the first
# sequence while the value should come from
# the second equence
key = seq[0]
val = seq[1]
if seq[0] not in new_formdic: # if the dictionary does not have any of those keys
# then it should take each of the list of items
# in the first sequence as keys
new_formdic[seq[0]] =val # It should also take each of the items in the list
# of the second sequence sequence as values
return new_formdic
In [9]:
# we call the function to see the dictionary so formed
myform()
Out[9]:
In [ ]: