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



Friday, 4 November 2016

Python Dictionary Comprehension - 'dict' type

Hello readers! This is another article of our tutorial series on Python 'Python on Terminal' and in this article we will have an introduction with another data structure or datatype in Python - 'Dictionary' (Dictionaries, in plural form). In some of previous articles, we have learned about two other data structures - Python Strings and Python Lists, Python Lists being Ordered collection of data (or Python objects, in more correct words). Ordered as every element in a list is associated with a positional parameter or offset or index. But, in a Python Dictionary, there is no indexing. Instead, every element is stored and accessed using a unique 'key', in the dictionary. A key is just a human-readable and meaningful name used to identify a value stored in the dictionary, which in more expressive than using an index. In short, a Python dictionary is a collection of data in the form of key:value pairs enclosed in curly braces { }, analogous to 'hash tables', which makes search operations faster with the use of dictionaries.

python-dict

Needless to mention here, Python dictionaries, just like everything in Python, are also objects and they belong to Python built-in dict class. Lets now know more about dictionary in more details.

Creating a Dictionary

To begin with, let's create simplest dictionary in the world - a blank dictionary. To create so, we need to complete the formalities by including 'nothing' within curly braces. This can also be done using Python built-in function dict() as shown below-

>>> myDict = {}
>>> myDict
{}

# Using 'dict()' function
>>> myDict2 = dict()
>>> myDict2
{}

Now, we use some key:value pairs to create a non-empty dictionary. These keys and values can be any Python object, but do remember that, a key must be unique across the dictionary or the value associated with it will be overwritten. Also, dictionary keys must be Python objects which are not mutable. That means, we can use strings and tuples as dictionary keys, but not lists.

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

We learn an important property of Python dictionaries here. If you observe carefully, while creating the dictionary, we've mentioned 'Spain' : 'Barcelona' pair first and then 'England' : 'Leicester City'. But, it has not displayed them in the same order. This is because, unlike Python Lists, Python dictionaries are Unordered Collection of data, as there are no positional parameters associated with them. Let us create some more dictionaries-

# 'str' as Key and 'list' as Value
>>> myDict = {'Spain' : ['Barcelona', 'Real Madrid'], 'England' : ['Leicester City', 'Arsenal']}
>>> myDict
{'England': ['Leicester City', 'Arsenal'], 'Spain': ['Barcelona', 'Real Madrid']}

# Lists are mutable and cannot be used as keys
>>> myDict = {['Barcelona', 'Real Madrid']: 'Spain', ['Leicester City', 'Arsenal'] : 'England'  }
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

# Nested dictionary - 'dict' as Value
>>> myDict = {'Ronaldo' : {'Club' : 'Real Madrid', 'Country' : 'Portugal', 'Jersey Number' : 7}, 'Messi' : {'Club' : 'Barcelona', 'Country' : 'Argentina', 'Jersey Number' : 10} }
>>> myDict
{'Messi': {'Club': 'Barcelona', 'Country': 'Argentina', 'Jersey Number': 10}, 'Ronaldo': {'Club': 'Real Madrid', 'Country': 'Portugal', 'Jersey Number': 7}}

# 'int' type are non-mutable and can be used as Keys
>>> RealMadridDict = {7 : 'Cristiano Ronaldo', 11 : 'Gareth Bale', 9 : 'Karim Benzema'}
>>> RealMadridDict
{9: 'Karim Benzema', 11: 'Gareth Bale', 7: 'Cristiano Ronaldo'}

Great! Now, we check what type the variable myDict belongs to, using type() function.

>>> type(myDict)
<type 'dict'>

As we've seen earlier, there is a Python built-in dict() function, with which we can create dictionaries. We have already created an empty dictionary using it and this time we create a non-empty dictionary using the syntax dict(key1='value1', key2='value2') as shown below-

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

Basic Operations on a Dictionary

1. Adding elements to a dictionary

First thing to note is that - Dictionaries are mutable Python objects, as they can be modified. Now we check this by modifying a dictionary, by adding elements to a dictionary. For this, we simply create a key:value pair as dict_name[key] = value. This will create a key with name key in a dictionary dict_name and assign a value value to it.

>>> myDict = {'England': 'Leicester City', 'Spain': 'Barcelona'}
>>> myDict
{'England': 'Leicester City', 'Spain': 'Barcelona'}
>>> myDict['Italy'] = 'Juventus'
>>> myDict
{'Italy': 'Juventus', 'England': 'Leicester City', 'Spain': 'Barcelona'}
>>> myDict['Germany'] = 'Bayern Munich'
>>> myDict
{'Italy': 'Juventus', 'Germany': 'Bayern Munich', 'England': 'Leicester City', 'Spain': 'Barcelona'}

Again, dictionaries are not the ordered collections.

2. Accessing the elements of a dictionary

To access the elements of a dictionary, we need to make use of dictionary keys as shown below. If the key is not present in the dictionary, a 'KeyError' exception (or error in simple words) is raised. The syntax for accessing dictionary items is - dict_name[key_name]

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

>>> myDict['England']
'Leicester City'

>>> myDict['France']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'France'

3. Deleting elements from a dictionary

We can add elements to a dictionary using a key, similarly, we make use of a dictionary key to delete the elements from that dictionary and Python built-in del function. The syntax for deletion is - del dict_name[key].

>>> myDict
{'Italy': 'Juventus', 'Germany': 'Bayern Munich', 'England': 'Leicester City', 'Spain': 'Barcelona'}

# Deleting 'Italy': 'Juventus' using key
>>> del myDict['Italy']
>>> myDict
{'Germany': 'Bayern Munich', 'England': 'Leicester City', 'Spain': 'Barcelona'}

# Deleting 'Germany': 'Bayern Munich' using key
>>> del myDict['Germany']
>>> myDict
{'England': 'Leicester City', 'Spain': 'Barcelona'}

4. Updating values in a dictionary

Again, dictionary keys are very useful in this case. We can modify the value associated with a key using the key itself. Just assign a new value to the existing key - dict_name(key) = new_value.

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

# Changing 'Leicester City' to 'Liverpool'
>>> myDict['England'] = 'Liverpool'
>>> myDict
{'England': 'Liverpool', 'Spain': 'Barcelona'}

5. Length of a dictionary

Length of a dictionary is nothing but the number of key:value stored in the dictionary. We can get this count using the Python built-in function len() as - len(dict_name).

>>> myDict
{'England': 'Liverpool', 'Spain': 'Barcelona'}
>>> len(myDict)
2

>>> myDict['Germany'] = 'Bayern Munich'
>>> myDict
{'Germany': 'Bayern Munich', 'England': 'Liverpool', 'Spain': 'Barcelona'}
>>> len(myDict)
3

6. Check if a key exists in a dictionary

We can use in keyword so as to check if a key exists in a dictionary. It will return boolean value True or False based on the situation. The syntax for this is - in

>>> myDict
{'Germany': 'Bayern Munich', 'England': 'Liverpool', 'Spain': 'Barcelona'}

# Is 'Germany' a dictionary key ?
>>> 'Germany' in myDict
True

# Is 'France' a dictionary key ?
>>> 'France' in myDict
False

7. Important dictionary methods

For the scope of this article, we limit our discussion on only three important dictionary methods - keys(), values and items(). The name of former two methods hints at what they are used for. If you've guessed correctly, the keys() method when called on a dictionary, returns a list of all dictionary keys. Similar is the case for values() method, it returns a list of all dictionary values. The third method, items, returns a list of tuple pairs, wherein the first element in the tuple is a key and second element is the value associated with it.

>>> myDict
{'Germany': 'Bayern Munich', 'England': 'Liverpool', 'Spain': 'Barcelona'}

# 'keys()' returns a list of keys
>>> myDict.keys()
['Germany', 'England', 'Spain']

# 'values()' returns a list of values
>>> myDict.values()
['Bayern Munich', 'Liverpool', 'Barcelona']

# 'items()' returns a list of (key, value) tuple pairs
>>> myDict.items()
[('Germany', 'Bayern Munich'), ('England', 'Liverpool'), ('Spain', 'Barcelona')]

Thus, as these methods return a list type object, we can iterate over it using a for .. in statement. Don't worry if you don't understand it, we will have a separate article on for loops. It's sufficient to know that keys(), values() and items(), all of them return an iterable - a list.

>>> for key in myDict.keys():
...     print key
...
Germany
England
Spain

>>> for value in myDict.values():
...     print value
...
Bayern Munich
Liverpool
Barcelona

>>> for key,value in myDict.items():
...     print key + ' = ' + value
...
Germany = Bayern Munich
England = Liverpool
Spain = Barcelona

That's all for now! In this article, we learned some of the properties of Python dictionaries, we created dictionaries in different ways, we added elements in the dictionaries, we deleted the entries from dictionaries, we calculated the number of entries and we worked on three of the important methods related to dictionaries. In this next article, we would learn some more dictionary methods along with examples. I hope you enjoyed reading this article, please share your views and opinions in the comment section below. Thank you.

This article is originally published at www.codeninja.in - Python Dictionaries - Introduction and Basic Operations

0 comments:

Post a Comment