Python : Crash Course Part 5 – Dictionaries

Curly brackets, a key & a value to the key – these are the three components of a dictionary in python. The key name has to be passed within single quotes if the key name is a string, single quotes is not required if the key is an integer.

In [1]: dictionary = {'key1':100}

Now dictionary[0] won’t work here as the data retrieval using a dictionary is already controlled by the keys within the dictionary.

If I want to retrieve the value 100 from the above dictionary, the syntax would be :

In [2]: dictionary['key1']
Out[2]: 100

We can also feed a list within a dictionary as shown below :

In [3]: dictionary={'k1':[1,2,3]}
In [4]: dictionary['k1']
Out[5]: [1,2,3]

If I want to retrieve just a number of my choice from the list, which is within the dictionary then the syntax would be :

In [6]: dictionary['k1'][2]
Out[7]: 3

Note that data retrieval method still holds good as it did when we explored indexing in python. We can also have a nested dictionary in python :

In [8]: dictionary{'k1':{'nested_dictionary'[1,2,3]}}

How would I retrieve the number 3 from the above dictionary, let me know in the comments below.

Let’s move on to Tuples.

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s