Introduction to Linux - A Hands on Guide | Linux Bible | Linux From Scratch | A Newbie's Getting Started Guide to Linux | Linux Command Line Cheat Sheet | More Linux eBooks



Tuesday, 8 November 2016

Python Dictionary Methods

Hello readers! This is the 11th article of our tutorial series on Python - 'Python on Terminal', and we will be studying 'Dictionary methods' in Python in this article. In the last article on Python dictionaries, we learned to create dictionaries and basic operations associated with them. We also learned three of the important dictionary methods - keys(), values and items(). In this article, we will be covering some more dictionary methods with their examples. Let's begin !

Python dictionary methods

First of all, we check what all methods are associated with Python dictionaries and we use Python built-in dir() function to list all of them. For this, we need to create a dictionary and provide it as an argument to dir() function.

>>> myDict = {'Spain' : 'Barcelona', 'England' : 'Leicester City'}
>>> dir(myDict)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']

As we've seen in case of Strings and Lists, there are Magic Methods for Python dictionaries too, which Python uses internally. We need not care about them now and start our discussion on dictionary methods, right away.

1. clear() Method :

Well, the name of the method says it all. This method removes all the entries from the dictionary.

>>> myDict
{'England': 'Leicester City', 'Spain': 'Barcelona'}
>>> myDict.clear()
>>> myDict
{}

2. copy() Method :

This method when called on a dictionary, returns a copy of the dictionary on which it is called. This method is used to create a copy of a dictionary, or to copy the contents of a dictionary to other dictionary.

>>> myDict1
{'England': 'Leicester City', 'Spain': 'Barcelona'}
>>> myDict1.copy()
{'England': 'Leicester City', 'Spain': 'Barcelona'}
>>> myDict2 = myDict1.copy()
>>> myDict2
{'England': 'Leicester City', 'Spain': 'Barcelona'}

3. fromkeys() Method :

This method is used to create a new dictionary using Python built-in dict type (constructor is the more correct word). It accepts one mandatory argument of list type, say keylist and one optional argument, say value. With the list provided, it returns a dictionary having keys mentioned in the list. The value we mention in the optional argument is set as the default value of all the keys. If no value is mentioned, None will be the values set. The syntax to use this method is - dict.fromkeys(keylist[, value])

>>> dict.fromkeys(['England', 'Spain'])
{'England': None, 'Spain': None}

>>> dict.fromkeys(['England', 'Spain'], "I don't know!")
{'England': "I don't know!", 'Spain': "I don't know!"}

4. get() Method :

This method also accepts a mandatory argument, say key and an optional argument, say default. When we call this method on a dictionary, it returns the value corresponding to the key mentioned. If key is not present in the dictionary and no optional argument is provided, it would return None. In this case, if optional value (default) is provided, it would return the default value. The syntax for using this method is - dict_name.get(key_name [, default_value]).

>>> myDict
{'England': 'Leicester City', 'Spain': 'Barcelona'}

>>> myDict.get('Germany')
>>> myDict.get('Germany', 'Bayern Munich')
'Bayern Munich'

5. has_key() Method :

This method requires a mandatory argument, that refers to the key to be looked for in the a dictionary. When we call this method on a dictionary, it checks whether the key mentioned in the argument is present in the dictionary. It returns True if present, False otherwise. The syntax for this method is - dict_name.has_key(key_name).

>>> myDict
{'England': 'Leicester City', 'Spain': 'Barcelona'}

>>> myDict.has_key('Spain')
True

>>> myDict.has_key('France')
False

6. items() Method :

If you have read the last article on Python dictionaries, you must have read about this method. This method when called on a dictionary, it returns a list of tuples of key-value pairs in the form [(key1, value1), (key2, value2), ... , (keyN, valueN)], where (key1, value1) is a tuple of key-value pair. Let's check this.

>>> myDict
{'England': 'Leicester City', 'Spain': 'Barcelona'}
>>> myDict.items()
[('England', 'Leicester City'), ('Spain', 'Barcelona')]
One thing to be noted here, this method returns a list, i.e. an iterable. Thus, using this method along with for .. in, we can iterate over all the key-value pairs in the dictionary and perform operations on them.

7. iteritems() Method :

We've seen items() returning a list of tuples of key-value pairs, which would require more memory, if dictionary was too long. Now, we have iteritems() method, that returns an iterator. This iterator lets us iterate over an item (key-value pair) at a time, so that memory is required to store only one key-value pair for that iteration. In the next iteration, the previously stored key-value pair is flushed and next pair is picked up and stored.

>>> myDict
{'England': 'Leicester City', 'Spain': 'Barcelona'}

>>> myDict.iteritems()
<dictionary-itemiterator object at 0x7f9c6deea208>

>>> type(myDict.iteritems())
<type 'dictionary-itemiterator'>

>>> for (key, val) in myDict.iteritems():
...     print 'Key is ' + str(key) + ' and Value is ' + str(val)
...
Key is England and Value is Leicester City
Key is Spain and Value is Barcelona

8. keys() Method :

This method when called on a dictionary, returns a list of keys present in the dictionary. Similar to iteritems(), we have iterkeys() method also, that returns a key-iterator object.

>>> myDict
{'England': 'Leicester City', 'Spain': 'Barcelona'}

>>> myDict.keys()
['England', 'Spain']

>>> myDict.iterkeys()
<dictionary-keyiterator object at 0x7f9c6deea208>

>>> type(myDict.iterkeys())
<type 'dictionary-keyiterator'>

>>> for key in myDict.iterkeys():
...     print 'Key = ' + key
...
Key = England
Key = Spain

9. values() Method :

This method when called on a dictionary, returns a list of values present in the dictionary. As we have iteritems() and iterkeys() methods, we also have itervalues() method, which returns a value-iterator object.

>>> myDict
{'England': 'Leicester City', 'Spain': 'Barcelona'}

>>> myDict.values()
['Leicester City', 'Barcelona']

>>> myDict.itervalues()
<dictionary-valueiterator object at 0x7f9c6deea208>

>>> type(myDict.itervalues())
<type 'dictionary-valueiterator'>

>>> for val in myDict.itervalues():
...     print 'Value is ' + val
...
Value is Leicester City
Value is Barcelona

10. pop() Method :

The syntax for this method is - dict_name.pop(key_name [, default_value]), where default_value is optional argument. This method when called on a dictionary, it returns the the value associated with the key provided in the argument. If the key is not present in the dictionary and default_value is not mentioned, it will raise an exception (or an error). If the default_value argument is provided and if key is not present, it will return default_value instead of raising an exception.

>>> myDict
{'England': 'Leicester City', 'Spain': 'Barcelona'}

>>> myDict.pop('England')
'Leicester City'
>>> myDict
{'Spain': 'Barcelona'}

>>> myDict.pop('Germany')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Germany'

>>> myDict.pop('Germany', 'Key not present !!')
'Key not present !!'

11. popitem() Method :

This method does not need any arguments to be provided. It just returns a tuple of a random/arbitrary key-value pair and removes it from the dictionary. If the dictionary is empty, it will raise an exception, as there is nothing to pop out from the dictionary.

>>> myDict = {'England': 'Leicester City', 'Spain': 'Barcelona'}

# Call 'popitem()' and check the contents
>>> myDict.popitem()
('England', 'Leicester City')
>>> myDict
{'Spain': 'Barcelona'}

# Check the type of popped out item
>>> type(myDict.popitem())
<type 'tuple'>
>>> myDict
{}

# 'popitem()' method on an empty dictionary
>>> myDict.popitem()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'popitem(): dictionary is empty'

12. setdefault() Method :

This method is very much similar to get() method. The difference is that, we have an optional parameter in case of get() method, which is returned if the key we are looking for is not present in the dictionary. While, setdefault() method does not only returns the 'default' value mentioned, but it also sets the value to the key mentioned (if key is not present in the dictionary).

>>> myDict
{'England': 'Leicester City', 'Spain': 'Barcelona'}

# 'get()' method - Key is not present, will return default value, but not set it
>>> myDict.get('Germany', 'Bayern Munich')
'Bayern Munich'
>>> myDict
{'England': 'Leicester City', 'Spain': 'Barcelona'}

# 'setdefault()' method with key present, returns the associated value
>>> myDict.setdefault('England', 'Bayern Munich')
'Leicester City'
>>> myDict
{'England': 'Leicester City', 'Spain': 'Barcelona'}

# 'setdefault()' method with key not present, returns the default value
>>> myDict.setdefault('Germany', 'Bayern Munich')
'Bayern Munich'
# also sets the value against the key
>>> myDict
{'Germany': 'Bayern Munich', 'England': 'Leicester City', 'Spain': 'Barcelona'}

13. update() Method :

This method accepts another dictionary as a mandatory argument and merges all the key-value pairs into the dictionary on which the method is called, very similar to 'concatenation'. In this case, if some key is common to both the dictionaries, it's value will be overwritten.

>>> myDict
{'England': 'Leicester City', 'Spain': 'Barcelona'}
>>> myDict2 = {'Germany' : 'Bayern Munich'}
>>> myDict.update(myDict2)
>>> myDict
{'Germany': 'Bayern Munich', 'England': 'Leicester City', 'Spain': 'Barcelona'}

# A dictionary with common key 'England'
>>> myDict3 = {'England' : 'Manchester City'}
>>> myDict.update(myDict3)
>>> myDict
{'Germany': 'Bayern Munich', 'England': 'Manchester City', 'Spain': 'Barcelona'}

14. View Objects, viewkeys(), viewvalues() and viewitems() Methods :

We have Python views in Python 2.7 onward. We can consider these methods to be very similar to iteritems(), iterkeys() and itervalues() methods. The difference being that, iteritems() method returns an iterator object while viewitems() returns dynamic view of the dictionary items. They are dynamic, as whenever changes are made in dictionary, those get reflected in the views.

>>> myDict = {'England': 'Leicester City', 'Spain': 'Barcelona'}
>>> myDict.viewitems()
dict_items([('England', 'Leicester City'), ('Spain', 'Barcelona')])
>>> myDict.viewkeys()
dict_keys(['England', 'Spain'])
>>> myDict.viewvalues()
dict_values(['Leicester City', 'Barcelona'])

>>> type(myDict.viewitems())
<type 'dict_items'>
>>> type(myDict.viewkeys())
<type 'dict_keys'>
>>> type(myDict.viewvalues())
<type 'dict_values'>

# A change is made to the dictionary
>>> myDict['Germany'] = 'Bayern Munich'
>>> myDict.viewitems()
dict_items([('Germany', 'Bayern Munich'), ('England', 'Leicester City'), ('Spain', 'Barcelona')])
>>> myDict.viewkeys()
dict_keys(['Germany', 'England', 'Spain'])
>>> myDict.viewvalues()
dict_values(['Bayern Munich', 'Leicester City', 'Barcelona'])

With this, we have come to the end of this article. We have learned a bunch of dictionary methods in this article along with their examples. In the next article, we will be learning about another data structure in Python - Tuple. Please let us know about your views and opinions in the comment section below and stay tuned. Thank you.

This article is originally published at www.codeninja.in - Introduction to Python Dictionary Methods

0 comments:

Post a Comment