Skip to main content

Python crash course: Dictionary



Dictionary in Python 

Till now we have discussed about strings and lists, in this article we will be discussing about dictionaries. Dictionaries are a kind of mapping between keys and values. Till now all the object types we have covered their elements can be accesses by their index, it is easy but there are many situations when we want to access the elements of an object by some other means like their name may be, but because of the constraines of the list and string typed objects we can not do that but with dictionary types objects you can access any of the element of the object with their keys defined by you(programmers), you can visualize them as hash tables.
1.) How do we create Dictionary in Python
2.) Getting and updating values in Dictionaries
3.) Nesting in Dictionaries
4.) Some inbuilt methods of dictionaries

The following figure explains the basic concept of mapping, here you can see that how the keys of a dictionary is mapped with the elements of the dictionary.
mapping image not found
There are two parts of a python dictionary, one is key and one is value.

How do we create a Dictionary in Python

In [1]:
# We write the key and value pairs "key:value" in curly brackets separated with commas.
dict_one = {'key_one':'value_one', 'key_two':'value_two'}
In [2]:
# we can access the values with their keys as shown below
dict_one['key_two']
Out[2]:
'value_two'
We can hold every kind of element in the dictionary (values), but in the field of keys we can only put the immutable data object typed elements like string, tuple. We can not use list or dictionary in the field of keys. This particular feature of the dictionary data type is concerned with the accidental changes made to the dictionary, and by accidental I mean the changes which may happen during the execution of the program. So, if the data type of the keys will be immutable then there will not be any chance for it to get modified during the execution of the program.
In [3]:
dict_two = {'key_one':420,'key_two':['a', 'b', 'c'],'key_three':('abc', 2)}

Getting and updating values in the dictionary

In [4]:
# Lets check the items of the dictionary by calling them with the key.
dict_two['key_two']
Out[4]:
['a', 'b', 'c']
In [5]:
# We can also dig deeper and call another element of the element called
dict_two['key_two'][0]
Out[5]:
'a'
In [6]:
# We can even call the inbuilt methods of the returned item
dict_two['key_two'][0].upper()
Out[6]:
'A'
We can alter any of the values by accessing it with its key, Lets see the example below:
In [7]:
dict_two['key_one']
Out[7]:
420
In [8]:
# Lets add something to it and reassign to the same key
dict_two['key_one'] = dict_two['key_one'] - 123
In [9]:
dict_two['key_one']
Out[9]:
297
If you remenber the case of lists there we were not able to create a new wlement just by assigning a new element to a new index, we had to use .append method to do soWe can use simple assignment to add a new element to the dictionary too, that means if the dictionary is even empty we can add a new element by simple assignment.
In [10]:
# Creating a new dictionary
dict_three = {}
In [11]:
# Adding the first element using assignment
dict_three['creature'] = 'mammal'
In [12]:
# Lets add another element to the dictionary
dict_three['mammal'] = 'horse'
In [13]:
# We can add any type of object
dict_three['number_of_creatures'] = 89
In [14]:
# Printing the dictionary
print(dict_three)
{'creature': 'mammal', 'mammal': 'horse', 'number_of_creatures': 89}

Nesting in Dictionaries

In the previous article we have seen that how we can create nested lists, we can do the same thing with dictionaries also. Let's see how we create a nested dictionary and what are the rules to do so.
In [15]:
# Lets create dictionary inside a dictionary which is already inside a dictionary
dict_three = {'key_one':{'nested_key_one':{'nested_2_key_one':'value_one'}}}
I know that was to much of inception write? Ok now let's access the elements of the dictionary and see how deep we can dig.
In [16]:
# Keep calling the keys
dict_three['key_one']['nested_key_one']['nested_2_key_one']
Out[16]:
'value_one'

Some inbuilt methods of dictionaries

we have seen almost every topic of dictionaries, but there is something still missing and that is the inbuilt function. Inbuilt functions provide a lot of ease when we are writing the code because there are some operations which we use very frequently and if we have to write them for every program, it will be really irritating so creating some common methods and attaching them with the classes is a really smart move. Now let's see some of the inbuilt methods which we can call on dictionaries.
In [17]:
# Recreate the firs dictionary we used "dict_one"
dict_one = {'key_one':'value_one', 'key_two':'value_two'}
In [18]:
# If we need to return the list of all keys
dict_one.keys()
Out[18]:
dict_keys(['key_one', 'key_two'])
In [19]:
# If we need to return the list of all values of the dictionary
dict_one.values()
Out[19]:
dict_values(['value_one', 'value_two'])
In [20]:
# Now if we want to return the list of key-value pairs of the dictionary
dict_one.items()
Out[20]:
dict_items([('key_one', 'value_one'), ('key_two', 'value_two')])
We have covered the basic concept of dictionaries in python, We are moving at a very steady pace and we are covering even very small topics also so that when someone lookes at our article then he or she can get the material he or she is looking for. I hope you have understood the concept. If there is something I missed or there is some specific topics I should be covering please let meknow in the comment section. It really motivates me when you guys post your queries in the comment section. In the next article we will cover Tuples in python, tuples are very interesting topic because the are really helpfull in case of object creation and in processing multiple loops in a single loop, it will be fun covering tuples. Till then best of luck!

Comments

Post a Comment

RUNTIME