Pages

Sunday, January 10, 2021

Working with Dictionaries in Python

Dictionaries

Dictionaries (dict) are used to store the data based on a key value. Unlike Lists and Tuples, data in the dictionaries isn't stored based on the index. And, data in the dictionaries are specified using curly brackets with the key and it's corresponding value ({key1 : value1, key2 : value2,...}

Below are some of the features of dictionaries in Python. 
  • Dictionaries can hold data of different data types.
  • Data in the Dictionary can be amended. 
  • Data in the Dictionary needs to be accessed by using the key.
  • No duplicate key values are allowed in Dictionary (duplicate data can be present with different key).

In this post, we will see how to access the data from dictionary, amend the data for a specific key value and different methods associated with dictionary. 

Creating a dictionary in Python

A dictionary is created when the data (and corresponding key value) in curly brackets is assigned to a variable.

Creating dictionary in Python

In the above example,
  • 1, 2, "THREE", "FOUR" and 5 are the keys. Key doesn't necessarily be numeric but should be unique with in dictionary. 
  • "ONE", "TWO", 3, 4 and True are the values against the corresponding keys. Dictionary can hold the data of different data types. 
  • A value will always have a key associated and can only be accessed by using the key.
We just stated that key should be unique with in dictionary. What happens if we mention duplicate keys with in dictionary? Value passed against the key will replace the original value in the dictionary and will not have duplicate keys in the final dictionary. It can be understood better using the below example.

Creating dictionary in Python

In the above example, 
  • Line - 2: Key '1' is specified twice to create 'a_dict' dictionary. Data stored in the dictionary will only have the latest value assigned against key '1' ("ONE - UPDATED").
  • Lines - 6 & 7: 'a_dict' is created without any duplicate values and data for key '1' is updated after dictionary is created. 
  • Both these dictionaries would return the same key and values. 
  • Line - 7: Data in the dictionary can be accessed or updated by mentioning it's key value with in square brackets.
Print dictionary in Python

Adding new data (and key) to Dictionary

There is no method like add() or append() to add a key (and data) to a dictionary. Like accessing or updating the data by using a key value, New key can be added by specifying new key with in square brackets and assigning data to it. 

dictionary_variable["new key"] = "New Data to be Added"

Adding new key to dictionary in Python

In the above example, Key '4' isn't specified when creating dictionary 'a_dict' (Line - 2). When the data is assigned to the new key (Line - 6), key is automatically added to the dictionary.

Dictionary in Python

There is one other way of adding data to the dictionary by using setdefault() method. setdefault() does more than just adding a new value, this can be easily understood with an example.

What is the use of setdefault method in Python

In the above example, 
  • Line - 6: We are passing new key and value to setdefault method. This would insert the new key and value into the dictionary and returns the value, so that the value can be printed.
  • Line - 12: We are passing the existing key with updated value. If the key already present in the dictionary, second argument has no affect in the operation. Data passed won't be updated and current data for the key is returned. 
  • Line - 17: We are passing new key with no value. As the key isn't present in the dictionary new entry will be written. No data is passed, so Python would add 'None' by default and returns the same.
print dictionary in Python

Removing the data (and key) from Dictionary

There are couple of methods 'pop()' and 'popitem()' to remove the data (and corresponding key) from the dictionary. Let's have a look at each of these methods. 

pop() - This method accepts the key as an argument and removes the corresponding value from dictionary. This method would also return the data that is being deleted.

Delete an item from the dictionary in Python

In the above example (Line - 7), pop() should remove the value "TWO" from the dictionary 'a_dict' and return the same, this would be printed to the console. print statement before and after this would show the dictionary before and after the data is removed from the dictionary. 

Remove data from the dictionary in Python

popitem() - This method works slightly different from pop(). This method doesn't accept any arguments and deletes the last value in the dictionary by default. Unlike pop(), popitem() returns both key and corresponding value (being deleted) as a tuple. 

Remove last value from the Dictionary in Python

In the above example (Line - 6), popitem() should remove the last item "THREE" and return both key (3) and value ("THREE") as a tuple. 

Print Dictionary in Python

We will have a look at some more dictionary methods in the next part.


If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

No comments:

Post a Comment

Exception Handling in Python (try - except-else-finally)

Exception Handling in Python Exception handling is key for any programming language. When an exception occurs Python interpreter stops execu...