Working on Python Dictionaries

As dictionary can store many key-value pairs in fact it can store millions of items. So to handle or work with all those items python lets us loop through the dictionary. There exists many ways to loop through all dictionary items by using the keys or the value

1) Looping in Dictionary through all items One of the simplest way (at least for me) is using a for loop. So before working with the key-value pairs let us make a dictionary to store the information of a student.

student_1 = {'name' : 'Samridhi' , 'nationality' : 'Indian' , 'Stream' : 'Electronics and Telecommunication' , 'age' : '19'}

Use of for Loop – To get a single item of a dictionary we can simply use the key value but to print the whole dictionary we use the for loop. We select the two variables names to hold the key and value of each item in dictionary. We can choose any name or any character as variable. The for loop stores each item in those variables. The method items() is used to return the list of items.

Example – To print the information of student_1 in an organized way.

for key, value in student_1.items():
 print("\nKey: " + key)
 print("Value: " + value)

Output ->

Key: age
Value: 19

Key: Stream
Value: Electronics and Telecommunication

Key: nationality
Value: Indian

key: name
value: Samridhi

This type of looping works well with millions of data and it also helps to see for choices of many people when the value remains same for many but key (name of a person) keeps on changing.

This way does not give all the key-value pairs in the same order as entered because looping does not take of that. So the items we get are in a unpredictable order. If you want a sorted dictionary to get the name of millions of students in an order makes it more readable so a sorted() function can be used with the for loop.

2) Looping in Dictionary through keys – The method keys() of using the keys of any item is used when you don’t have to work with all the values in the dictionary. Like if you just want to know the name of students participated in a certain competition and don’t want to know in which game they are participating we can just get the keys of dictionary (names of students).
Example: In a college fest there are 3 sports category but we want only those students who participate in any sport.

College_fest = {
'sam': 'basketball',
'vikky': 'cricket',
'rachi': 'football',
'yashu': 'basketball',
}

for name in College_fest.keys():
    print(name.title())

Output ->

Sam
Vikky
Rachi
Yashu

Looping in dictionary through keys() method is default behavior for looping in dictionary so for name in College_fest: is same as for name in College_fest.keys():

We can use the key() method to work with items explicitly and this can also be used in many ways like i want to check if a certain person is coming to an event or not.
Example – Check the list of students if Rashmi is present if not call her to play any game.

if 'rashmi' not in College_fest.keys() :
    print("Rashmi come to register your name for college fest!")

Output ->

Rashmi come to register your name for college fest!

3) Looping in Dictionary through Values – In the previous method we were more concerned with keys but here our main focus is on the values. The values() method is used to get the values stored in the dictionary. Like if you only want to know the name of sports that are in the college fest.
Example –  Get the name of all the games in the College_fest.

print("These are the games in the college fest -")
for game in College_fest.values():
    print(game.title())

Output ->

These are the games in the college fest -
Basketball
Cricket
Football
Basketball

But here the game basketball repeats itself  This method results in a repetitive list of values. This can be used in some other examples where you would require all the values but here we want a list without repetitions. In this case set comes to rescue. A set only stores unique values. When a list is wrapped around a set python identifies all the unique items and displays them as a set of unique items.
Example – To display a set of games in the college fest.

print("These are the games in the college fest -")
for game in set(College_fest.values()):
    print(game.title())

Output ->

These are the games in the college fest -
Basketball
Cricket
Football

So here is the list of games in the college fest.

Next time i will be writing on nesting in dictionary.
Till then Happy Looping Dictionary!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s