Monday, October 15, 2018

Python Dictionary continued (Looping)

We know that a dictionary can contain either a few key-value pairs or millions of pairs. As a dictionary can contain large amounts of data, Python lets you loop through a dictionary. Dictionaries can be used to store information in a variety of ways; therefore, several different ways exist to loop through them. We can loop through all of a dictionary’s key-value pairs, through its keys, or through its values.

How to loop through a Dictionary's key-value pairs

Let's create a Dictionary user1 which will store username, first name, last name and  email Id of a user.

user1 = { 'username':'vswami',
          'first_name':'Vivek',
          'Last_name':'Swami',
          'email':'vswami@gmail.com',        
            }

If we want to access a single piece of information we can do it by using a print(), for example to access email id of user1 the syntax would be -

print(user1['email'])

See the screenshot below for program and output-





However our aim is to retrieve all the information about user1 and for this purpose we'll loop through user1 as shown below:

for key, value in user1.items():
    print("\nKey" + key)
    print("\nValue" + value)

See the screenshot below for program and output-


Just as we did in looping through lists we have created a for loop, the difference here is there are two more variables created namely key and value which will store the key and value in each key-value pair. Here we have flexibility to chose any name for these variables.

The items() method  returns a list of key-value pairs. The for loop then stores each of these pairs in the two variables provided (key and value in our case. Python doesn’t care about the order in which key-value pairs are stored; it tracks only the connections between individual keys and their values. So don't be surprised if the order in which the key value are displayed doesn't match according to the order in which they were stored.

For dictionary which which stores the same kind of information for many different keys, looping through all key-value pairs works perfectly. For example the programmers dictionary we created in our previous post, again shown below:

programmers = {'Bob':'Java', "Ted":'C', "Joey":'C++', "Chris":'Python',"Mac":'R'}

Let's make a simple program to print Key-value from the programmers dictionary. See the screenshot below for program and output- 



 Make some more programs and practice looping in dictionary.

How to loop through all the keys in a Dictionary

The items() returned both the key-value pair but in case we require only the key values for the item stored in a dictionary we can use keys() method. See the screenshot below for program and output-



Since for our looping we only keys(), Python pulled all the keys from the programmers dictionary, stored it in a value programmer and finally printed it.

Looping through the keys is actually the default behavior when looping through a dictionary, so this code would have exactly the same output as shown above-

for programmer in programmers:

     print(programmer)

If you want items in a certain order then sort the keys as they’re returned in the for loop. Just use the sorted() function to get a copy of the keys in order as shown below:

for programmer in sorted(programmers.keys()):   
   
    print(programmer) 



How to loop through all the values in a Dictionary

In case we require only the values for the item stored in a dictionary we can use values() method. See the screenshot below for program and output-



Since for our looping we only values(), Python pulled all the values from the programmers dictionary, stored it in a value programmer and finally printed it. Remember, this approach pulls all the values from the dictionary without checking for repeats which might work fine with a small number of values. Suppose my programmers dictionary has changed to -

programmers = {'Bob':'Java', "Ted":'C', "Joey":'C++', "Chris":'Python',"Mac":'R',"Tim":'R',"Joey":'R'}

Now I have three R programmers hence my output will display 'R' programming language three times but all I want is number of programming languages used in my projects. See the screenshot below for program and output-




To see each language chosen without repetition, we can use a set. A set is similar to a list except that each item in the set must be unique

 for programmer in set(programmers.values()):

See the screenshot below for program and output-



As seen in the output above when we use set() around a dictionary that contains duplicate items, Python identifies the unique items in the list and builds a set from those items. So set() pulled out unique languages in programmer dictionary, stored it in a variable programmer then finally printed it.

Practice the looping in all these conditions, try to make some realistic example to have a better understanding. Keep learning Python as Python is easy to learn!



Share:

0 comments:

Post a Comment