Monday, October 22, 2018

Inbuilt methods in Dictionaries

In Python the Dictionary data structures comes with some inbuilt methods. We have already used some of them so we'll cover up those methods in brief and then look into the other inbuilt methods.

1. The keys(), values(), and items() Methods

There are three dictionary methods that will return list-like values of the dictionary’s keys, values, or both keys and values: keys(), values(), and items(). The values returned by these methods are not true lists: They cannot be modified and do not have an append() method. But these data types (dict_keys, dict_values, and dict_items, respectively) can be used in for loops. Though we have already used these methods before, we'll see some more examples here. See the code below-

user1 = {'ename':'Nagaraju', 'age':'42'}

for user in user1.values():
   
    print(user)

In this program a for loop iterates over each of the values in the user1 dictionary. The output is shown in the screenshot below:



 
A for loop can also iterate over the keys or both key-value pairs. See the code below-

user1 = {'ename':'Nagaraju', 'age':'42'}

for user in user1.keys():
   
    print(user)

In this program a for loop iterates over each of the keys in the user1 dictionary. The output is shown in the screenshot below:


user1 = {'ename':'Nagaraju', 'age':'42'}

for user in user1.items():
   
    print(user)

In this program a for loop iterates over the items in the user1 dictionary. The output is shown in the screenshot below:



Notice that the values returned by the items() method are tuples of the key and value. If you want a true list from one of these methods, pass its list-like return value to the list() function. See the following program:

user1 = {'ename':'Nagaraju', 'age':'42'}

print(list(user1.keys()))

The list(user1.keys())) line takes the dict_keys value returned from keys() and passes it to list(), which then returns a list value shown in the screenshot below:






We can also use the multiple assignment trick in a for loop to assign the key and value to separate variables. See the following program:

user1 = {'ename':'Nagaraju', 'age':'42'}

for key,value in user1.items():
   
    print('KEY: '+ key + ' ,VALUE: ' + str(value))


The output is shown in the screenshot below:



 2. The get() method

This method is used to check whether a key exists in a dictionary before accessing that key’s value. It takes two arguments: the key of the value to retrieve and a fallback value to return if that key does not exist. See the following program:

fruits = {'Kiwis':'4', 'Oranges':'12'}

print(" I have " + str(fruits.get('Kiwis','0')) + ' Kiwis' )
print(" I have " + str(fruits.get('Oranges','0')) + ' Oranges' )
print(" I have " + str(fruits.get('Apples','0')) + ' Apples' )


The output is shown in the screenshot below:





As we don't have 'Apples' key in our fruits dictionary, the get() method returned the default value 0. If we try to print without using get() the code will return an error. The following program shows this behavior:

fruits = {'Kiwis':'4', 'Oranges':'12'}

print( (" I have " + str(fruits['Kiwis'])) + ' Kiwis' )
print( (" I have " + str(fruits['Oranges'])) + ' Oranges' )
print( (" I have " + str(fruits['Apples'])) + ' Apples' )


The output is shown in the screenshot below:



 3. The setdefault() method

The setdefault() method offers a way to set a value in a dictionary for a certain key only if that
key does not already have a value. For example:

user1 = {'name':'Nagaraju', 'age':'42'}

if 'email_id' not in user1:
   
    user1['email_id'] = 'mnraj@covrisolutions.com'
   
print(user1)

We have provided a default value for the 'email_id' key. In case if this key is not defined in the dictionary this default value of the key will be printed with the already defined keys. See the output below:



In Python, using the setdefault() method we can implement the same logic as follows:

user1 = {'name':'Nagaraju', 'age':'42'}

user1.setdefault('email_id','mnraj@covrisolutions.com')
   
print(user1)


Our output still remains the same as was before.


 Let's add one more default value as shown below:

user1 = {'name':'Nagaraju', 'age':'42'}

user1.setdefault('email_id','mnraj@covrisolutions.com')   
print(user1)

user1.setdefault('position','programmar')
print(user1)

The output is shown below:



As we can notice from the output, when the second time setdefault() was called a new key 'position' has been added to the dictionary with a default value of 'programmar'. Thus the setdefault() method is a nice shortcut to ensure that a key exists.

These were some inbuilt methods which can be very useful while modeling real world applications.
Make some more programs to master these methods. So keep learning Python as Python is easy to learn!




Share:

0 comments:

Post a Comment