De-mystifying Python Dictionaries !!!

In the python world Dictionaries are probably the most used Data-structures. They serves many purposes from storing and accessing configs to storing some kind of structured data. So, understanding and using them well is a great arsenal for a python developer.

So, in this short article I will try to explain some cool concepts of python dictionary. So, here we go :

let’s the code begin !!


* Dictionary default values :

Suppose we have a dictionary like this :

sample_dict = {
    "apple" : "red",
    "banana" : "yellow",
    "carrot" : "orange"
}

here, if we want to access value of any key, we can access it by calling the dictionary with that key, for example let’s say we have a function printing colour of the fruit passed as the arguments, it goes like this :

def fruit_color(fruit):
    return "Color of fruit is {}".format(sample_dict[fruit])

#if we call this function and pass it a fruit value it will #print it's color.

fruit_color_str = fruit_color("apple")

# result :
'Color of fruit is red'

# if we try to access a value of key which is not present in the #dict, then a KEY ERROR will be thrown by the python interpreter.
#But, in order to prevent key error and providing a default #response for non-existing keys we can user get() operator.

def fruit_color(fruit):
    return "Color of fruit is {}".format(sample_dict.get(fruit,"unknown color"))

# now if we call like :
a = fruit_color('pineapple')

# result:
Color of fruit is unknown color

So, .get() basically helps you to avoid KEY ERROR and return a default value for a key that does not exist in dictionary.




* Sorting Dictionaries :

Python dictionaries are un-ordered dataset i.e every-time time you access it , the order of keys will not be necessarily same. So, sorting dictionaries can be very handy sometimes. Python provides a way to do this : 

#Suppose we have dict like this :
demo_dict = {
    'nitish' : 23,
    'arpit' : 24,
    'raghav' : 21
}

#if we want to sort the dictionary lexicographically according to #keys we can do like this :

sorted(demo_dict.items(), key = lambda x: x[0])

# printing dict
print(demo_dict)

# result voila :
demo_dict = {
    'arpit' : 24,
    'nitish' : 23,
    'raghav' : 21
}

#you guessed it right, if we want to sort according to dict #values then we'll change lambda like this :

sorted(demo_dict.items(), key = lambda x: x[1])

#result :
demo_dict = {
    'raghav' : 21,
    'nitish' : 23,
    'arpit' : 24
}


* Weird Dict statement :

The output of the statement below can be little confusing but it explains many hidden concepts of Python. So, try to guess the output of the statement below :

# guess the output

dict_demo = {
    True : "a",
    1 : "b",
    1.0 : "c"
}

# take your time
#
#
#
# output is weird, right ??

print(dict_demo)

# result :
{ True : "c" }
Output is confusing , right ??

This is because the Boolean class in python is subclass of Integer class.
i.e True and False are considered as 1 and 0 integers respectively. Exception to this is when you print them by converting them to string.

Therefore, you can access the 0th and 1th index of a list like this :

demo_list = ["a","b","c","d"]

print(demo_list[False])
# result
"a"

print(demo_list[True])
# result
"b"

# It is quite cool, right ???

And, another thing to note here is that, when there are duplicate keys in a dict , python interpreter checks both the key equality and it’s hash value before concluding that they are same keys and replace the value with the later. That is why in the first example, we get the output as :

{True : "c"}

#because all True, 1 and 1.0 have same hash value and they are #equal, therefore remains same as True, but value of this key #gets updated to "c" as it is the latest key value.



* Merging two or more dictionaries together !

Many a times we want to merge two or more dictionaries together. In python 2.7 this can be easily achieved by using  .update()  operator.

# Example
dict_a = {
    "nitish" : 23,
    "arpit" : 24
}

dict_b = {
    "mudit" : 25
}

#Both of them can be merged like this :

dict_a.update(dict_b)

print(dict_a)

# result
{
    "nitish" : 23,
    "arpit" : 24,
    "mudit" : 25
}

But, what if we want to merge more than 2 dictionaries together. After python 3.6, there is a very nice way by which we can achieve this.

dict_a = {
    "nitish" : 23,
    "arpit" : 24
}

dict_b = {
    "mudit" : 25
}

#After python 3.6

dict_merged = {**dict_a, **dict_b}

print(dict_merged)

#result
{'nitish': 23, 'arpit': 24, 'mudit': 25}

This method comes very handy when we are merging more than two dicts together.




* Switch case statements using Dicts

There is no switch case statements in Python, so how can you achieve that ?? Python Dictionaries comes to the rescue here : 

#Suppose have scenario like this
def demo_func(data):
    if data==cond_1:
        return "Hi cond_1"
    elif data==cond_2:
       return "Hi cond_2"
    elif data==cond_3:
       return "Hi cond_3"
    elif data==cond_4:
       return "Hi cond_4"
    else:
        return "Hi unknown condition"

#The above code does not look pythonic and it looks very ugly
#The above code can be written in a very compact way using python
# Dictionaries like this :

def demo_func(data):
    return {
        'cond_1' : "Hi cond_1",
        'cond_2' : "Hi cond_2",
        'cond_3' : "Hi cond_3",
        'cond_4' : "Hi cond_5",
    }.get(data,'Hi unknown condition')

#the above codes looks much more pythonic, right ??
#that's the magic of dictionaries.   




So, above were some tricks and hacks about Dictionaries which I use on a regular basis in my python work. If you find them useful do comment and give your feedback. Thanks and Happy Hacking !!!

Good Luck !!!
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

This site uses Akismet to reduce spam. Learn how your comment data is processed.