Introduction to Python Dictionary

Python has a unique data type known as dictionary or python dictionary. It provides a very easy and flexible way to store and organize values. In essence, it is like a list as it can also store multiple values. There are two major difference between list and python dictionary and they are:-
  1. Indexes – List can only have an integer as index whereas python dictionary can have different data types indexes.
  2. Unsorted – Python list is a sorted data type whereas python dictionary is an unsorted data type. What this means is that there is no order of values in the dictionary. There is no first, second or last value. You cannot use list slicing methods on dictionary because of it. If you try to slice python dictionary like a list, then it will generate an error message.

Properties of Python dictionary

Let’s first create a dictionary data structure named as blog_details.

 # creating a python dicitonary
blog_details = {'name':'yoursdata', 'views':500, 'Years':1, 'articles':5}

#It will create a dictionary variable named as blog_details.
#We can read all of the values of a dictionary using print()

#output- {'name': 'yoursdata', 'views': 500, 'Years': 1, 'articles': 5}
  • As you can see, python dictionary is typed within braces {}.
  • blog_details is of dictionary type. You can check it by using type() function.
# Checking for data type

#output- dict
#dict is the data type
  • Python dictionary has two type of entries in its syntax i.e. KEYS and VALUES. In these two terms, syntax of dictionary is {KEYS: VALUES}
  • Each key-value pair is considered as a single item. KEYS are the index of VALUES.
  • For our blog_details dictionary, KEYS are ‘name’, ‘views’, ‘years’ and articles. Respective values for these keys are ‘yoursdata’, 500, 1 and 5.
  • KEYS are used to get the VALUES from a dictionary. Before using this, just make sure that the keys is present in the dictionary.
# Reading values from blog_details

#output- 'yoursdata'
  • Python dictionary doesn’t allow duplicate key. If you try to pass multiple entries for a key, it will store the latest value for that particular key.
# Creating a test dictionary with two entries for the same key
test_details = {'color':'black', 'term':2, 'color':'white'}

  • You cannot access dictionary stored values by using the positional index. Also, you cannot slice a dictionary using it.
# Trying to access dictionary items by using positions

#output- Error
# Trying to slice a dictionary using positional index

#output- Error
  • If you use a KEY which doesn’t exist in the dictionary, it will throw a KeyError message
# Trying to use a non_existent key

#output- KeyError

Methods and Function of Python Dictionary

  • len():- This gives the total length of any dictionary. Length of a dictionary is equal to the number of items present in it.
# checking the length of blog_details

#output- 4

#blog_details has 4 items i.e.pairs of keys and values

  • keys():- This method returns all available keys in the dictionary. It returns output in a list-like structure (called as dict_keys). These list-like values are different from a normal list in python as they don’t have append method. They can be used in FOR loop or can be converted into a normal list.
# using keys() to get all the keys from a dictionary

#output- dict_keys(['name', 'views', 'Years', 'articles'])
#We can see that output in in dict_keys type.
  • values():- This method returns all available values in the dictionary. Like KEYS(), it also returns output in a list-like structure (called as dict_values()) as mentioned above. These list-like values are different from a normal list in python as they don’t have append method. They can be used in for loop or can be converted into a normal list.
# using values to get all the values from a dictionary

#output- dict_values(['yoursdata', 500, 1, 5])
# we can see that ouput is in dict_values type.
  • items(): -This method returns all of the key-value pair present in the dictionary. This returns its output in a tuple. It is called dict_items. We can iterate over dict_items in a FOR loop using key and values.
# using items to get all items from a dicitonary

#output-dict_items([('name', 'yoursdata'), ('views', 500), ('Years', 1), ('articles', 5)])
#We can see that output is in dict_items type.
  • get():- As mentioned above, dictionary throws an error if you try to access values using a non-existent key. This can create a lot of problems. It will be a tedious task to make sure you are only checking for those keys which are available. Luckily dictionary has a method called GET(). It takes two arguments i.e. keys for which values to be checked, and a default fallback values if that key is not there in the dictionary.
# we will use get function to first get values from a dicitonay
# Case 1: When that key is present
blog_details.get('name', 'unknown')

#output- 'yoursdata'

# Case 2: When that key is not present
blog_details.get('domain', 'unknown')

#output- 'unknown'
  • setdefault():- This method can be used to either initialize new keys or to fetch the value if that key is already there.
 # using setdefault to initialize domain key
blog_details.setdefault('domain', 'technical')

#output- 'technical'
#domain as a key wasn't present in the blog_details.
#So, setdefault() will initialize it with value as 'technical'

#let's check the updated blog_details

#output-{'name':'yoursdata', 'views':500, 'Years':1, 'articles':5, 'domain':'technical'}
# As you can see, setdefault has initialized the "domain" key with "technical" value
#let's run setdefault() again for domain key with different values
blog_details.setdefault('domain', 'non-technical')

#output- 'technical'
#Now, blog_details already has 'domain' key so setdefault() will just return the
#stored value i.e. 'technical'

#output-{'name':'yoursdata', 'views':500, 'Years':1, 'articles':5, 'domain':'technical'}
#As key was already there, we can see blog_details is unchanged

Note :- In Python 2, there used to be 2 more functions i.e. cmp(dict1, dict2) and dict.has_key(key). Python 3 has removed these functions. And if you want these two fucntions, you can always write your code for this. cmp(dict1,dict2) was used to compare two dictionaries. dic.has_key(key) function was used to check whether a particular key is present in the dictionary or not.

Hopefully, this post will help you in learning Python Dictionary.  Let me know in the comment section if there is any doubt or problem regarding python dictionary. Please share and like the post, if you found it useful.

Leave a Reply

Your email address will not be published. Required fields are marked *