Practical program

Let's make some program  to understand the dictionary. Make a dictionary from two lists. Both the lists are of equal length. Take the lists as shown:

list1 = [1, 2, 3, 4, 5] 
list2 = ["a", "b", "c","d", "e"]

The list1 values act as the keys of the dictionary and the list2 values act as the values. The following is the program for it:

list1 = [1, 2, 3, 4, 5] 
list2 = ["a", "b", "c","d", "e"]
dict1 = {}
for index1 in xrange(len(list1)):
dict1[list1[index1]] = list2[index1]
print dict1

The output is as follows:

Output of exercise 1

Let's do the preceding exercise in one line:

 >>> list1 = [1,2,3,4,5]
>>> list2 = ["a", "b", "c","d", "e"]
>>> dict1 = dict([k for k in zip(list1,list2)])
>>> dict1
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
>>>

Just a one-liner code can make a dictionary from two lists. So, in the preceding example, we used the zip() function; zip() is a built-in function, which takes two lists and returns a list of two tuples, such as  [(key, value)]. Let's see an example of the zip() function:

>> list1 = [1,2,3]
>>> list2 = ["a","b","c"]
>>> zip(list1, list2)
[(1, 'a'), (2, 'b'), (3, 'c')]
>>>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.188.201