Methods for Dictionaries

As we discussed in the previous chapters, every Data Type has various methods specific to them, and here we will take about the important ones that are available for Dictionaries. Some of the methods we will learn are keys(), values(), items(), clear(), setdefault() and get(). They are quite easy to understand and are quite similar to what the name suggests. You can use the Python interpretor on the right side (black box on your Repl Window) for the following code.

The keys() method

Just as the name suggests, this method is used to output or fetch the keys of a dictionary. It's quite easy to use:

>>> car = {'color': 'Red', 'name': 'My Car', 'top Speed': '200 mph'}
>>> car.keys()
['color', 'name', 'top Speed']

Another interesting thing here, we can make a List of the keys or values.

>>> list(car.keys())
['color', 'name', 'top Speed']

The values() method

This method, just as above, helps us output or fetch the values of a dictionary. Here is an implementation:

>>> car = {'color': 'Red', 'name': 'My Car', 'top Speed': '200 mph'}
>>> car.values()
['Red', 'My Car', '200 mph']

The items() method

This method, is used to output all the items in a dictionary and once again, is quite easy to use:

>>> car = {'color': 'Red', 'name': 'My Car', 'top Speed': '200 mph'}
>>> car.items()
[('color', 'Red'), ('name', 'My Car'), ('top Speed', '200 mph')]

We can use the for loop and iterate over these values given by the methods we have seen so far.

>>> for i in car.items()
>>>        print(i)
('color', 'Red')
('name', 'My Car')
('top Speed', '200 mph')

Another way to use the for loop could be:

>>> for i,j in car.items():
>>>     print('Key: ' + i + ', Value: ' + j)
Key: color, Value: Red
Key: name, Value: My Car
Key: top Speed, Value: 200 mph

TASK: Now try using for loops for the values() and keys() method!

The clear() method

This method is used to clear the entire dictionary. The first question that usually arises is, why would we want to clear the entire Dictionary? How does that serve a purpose? Well, think about this example. You are running a really long program that uses various Dictionaries. These Dictionaries are used maybe once or twice and then they don't serve a purpose. This can cause memory issues on the computer. If we have a lot of Data loaded on your compiler which is not being used, then it's better to clear it. This saves time and computational costs. This is where the clear() method comes into play!

>>> car = {'color': 'Red', 'name': 'My Car', 'top Speed': '200 mph'}
>>> car.clear()
>>> car
{}

That's how easy it gets to clear an entire dictionary! We will do a more practical task using this feature in the coming units.

The get() method

To explain the use of this method, lets go through one small concept first. We haven't discussed how to check if an item (key or value) is present in a Dictionary or not. This is quite simple:

>>> 'color' in car.values()
False
>>> 'color' in car.keys()
True
>>> 'color' not in car.keys()
True

That's how easy it is!

However, there is one small problem with the method above. It gets tiring and inefficient to keep checking if a value we want is present in the Dictionary or not. To tackle this, Python has the get() method at disposal. This method helps us get the key we require and if it's not present, then we can input a default value to print (instead of using the Boolean True or False). The following implementation will help you understand better:

>>> print('The color of my car is ' + str(car.get('color', 'Black')))
The color of my car is Red

In the example, we have set the default value to Black in case there is no key called color in the Dictionary.

>>> print('I bought my Car in ' + str(car.get('yearOfPurchase', 2010)))
I bought my Car in 2010

The example above helps in understanding the importance of the default parameter better.

REMEMBER: If you don't input a default parameter, and the key doesn't exist, then you can expect a KeyError to pop up! Try it yourself.

The setdefault() method

This method is more like an add on to the last one we studied. With get() method we can get a key's value and in case it doesn't exist, we will get an error, unless we set a default value manually. Whereas, with setdefault() method, we can set a default value to any key with just one line of code.

Manually:

>>> car = {'color': 'Red', 'name': 'My Car', 'top Speed': '200 mph'}
>>> if 'yearOfBuy' not in car:
>>>     car['yearOfBuy'] = 2010
>>> car
{'color': 'Red', 'name': 'My Car', 'top Speed': '200 mph', 'yearOfBuy': 2010}

With the 'setdefault()' method:

>>> car = {'color': 'Red', 'name': 'My Car', 'top Speed': '200 mph'}
>>> car.setdefault('yearOfBuy', 2010)
2010
>>> car
{'color': 'Red', 'name': 'My Car', 'top Speed': '200 mph', 'yearOfBuy': 2010}

What if we want to change the value of a key with setdefault(), is that possible? Not really. What we need to observe here is that it just sets a default value, if a key exists already with a pair, then it won't make any difference to it:

>>> car = {'color': 'Red', 'name': 'My Car', 'top Speed': '200 mph'}
>>> car.setdefault('top Speed', '300 mph')
'200 mph'

Lets put this to some practical use with an example. We will count the number of 0's in the following String.

>>> stringExample = '04350043004325034500234350350000320450345000000043503405000003532'
>>>    count = {}
>>>    for i in stringExample:
>>>      if i == '0':
>>>        count.setdefault(i, 0)
>>>        count[i] = count[i] + 1
>>>    print(count)
{'0': 29}

TASK 1: Is there a way to make the code above more efficient? Try it

TASK 2: Modify the code to count all the characters in the String.

results matching ""

    No results matching ""