Learn the concept of Dictionaries in Python

0
3970
Python Tutorial – Advanced Topics

Python Tutorial – Advanced TopicsWhat are Dictionaries?
Dictionary is a Python built-in data type that is used to store collections of unordered key-value pairs.

Why Dictionaries?
Dictionaries offer the association of keys to their corresponding values. Each key refers to one (and only one) value in the dictionary. This not only facilitates storing and processing of data, but also enriches the whole process by enabling the user to store data in pairs. This greatly enhances searching and indexing operations.

What are the Features of Dictionaries?

  • Dictionaries are collections of key-value pairs.
  • Dictionaries are unordered: unlike lists that have values stored in a certain order based on the array index, dictionaries don’t maintain one order for its data items.
  • Data items are accessed by keys, not by indexes.

Syntax for Initializing Dictionaries
A dictionary name is an identifier (just like variable names, list names, and function names). Dictionaries are assigned values using the normal assignment operators ‘=’.

From the above statement, we can notice that:

  • Dictionaries are delimited by curly braces.
  • A key comes before its corresponding value.
  • Keys and values are separated by colons ‘:’
  • Like lists, pairs are separated from each others by commas ‘,’

Using Dictionaries

Reading the Value of a Specific Key
1
Remember that 3 and 1 are not indexes. They are keys.
2
Setting the Value of a Specific Key
3
Clearing an Entire Dictionary
We can clear a dictionary by deleting all existing key-value pairs. This can be done using the clear function.
4
Getting the Length of a Dictionary
The well-known function len (that we used before with lists and strings) returns the numbers of items (pairs) in a dictionary.
5
Verifying it is truly a Dictionary
We have seen before the type function that returns the type of the variable sent to it. If the argument passed to it is a dictionary, it should report so.
6
Converting an Entire Dictionary into a String
We can convert a dictionary into a string using the str function.
7
Deleting an individual Item from a Dictionary
To delete an individual item (pair) from a dictionary, we could use the del command. To identify the pair to be removed, it should be referenced by key.
8
Retrieving the List of Keys in a Dictionary
To get the list of keys in a dictionary, the keys method is used.
9
Retrieving the List of Values in a Dictionary
To get the list of values in a dictionary, the values method is used.
10
Adding a New Item to a Dictionary
To add (insert) a new pair to a dictionary, the same way we used before to change the value for a specific key is used, with one difference: the key that will be used is a new key that doesn’t exist in the dictionary.
11
Here, we added the new pair ‘Major’ : ‘Engineering’ using the usual assignment statement, by assigning the new value ‘Engineering’ to the new key ‘Major’. This dynamically extends the dictionary in place.

Retrieving the Dictionary Items in Tuple Pairs Format
To do this, the items method is used.
12
C Programming_1
Popping off a Dictionary Item for a Specified Key
The pop method returns the value for a provided key, then removes the item from the dictionary.
13
Popping off a Dictionary Item Randomly
The popitem method returns an item randomly from a dictionary, and removes that item.
14
Notice that after popping the three items out of the students dictionary, it became empty.

Merging Two Dictionaries into One
An entire dictionary can be copied (merged) into another dictionary using the update method. This method extends the dictionary it was called from, by inserting the items from the copied dictionary.
15
Notice that the students dictionary had initially two items. After using the update method to copy the items of the info dictionary into it, it has now four items.

Merging Two Lists to Create a Dictionary
The zip function can be used to merge two lists into a list of tuples. Passing the resulting list as an argument to the dict function returns the required disctionary.
16
* * * * * *

Example
Given the students dictionary, we need to traverse the entire dictionary to print the individual keys and the values corresponding to each one.
17
The same way we use to traverse a list (or a string) also applies here; a for loop that loops on the list of keys in dictionary (retrieved using the keys method).

Example
In this example, we are going to read the keys and values from a file, and store them in a dictionary.
Consider we have the following text file that contains students’ names and degrees.
18
We need to read the file, and store the read data in key-value pairs (dictionary).
The required script could look like this:
19
Now, let’s explain the script:

  • First, an empty dictionary is defined.
  • The file is open for read.
  • The contents of the file have been read into an array of lines using the readlines method.
  • For each element in the array of lines (i.e. for each line from the file), do the following:
    • Use the split method to split the line in hand into an array of strings. The first element in the resulting string is the student name, while the second is the grade (in a string format).
    • Add a new item to the students_grades dictionary. Use the first element in the linelist array (student name) as the key, and the second element (grade in string format) after being passed to the eval function to return its value as the value.

* * * * * *

In this article, we have talked about Dictionaries. Dictionaries are useful if you need to store data in key-values pairs. Dictionaries are unordered. Values can be accessed for reading, modification, or deletion using keys (unlike lists that depend on indexes).

I hope you find this article useful.
See you in another topic.

LEAVE A REPLY

Please enter your comment!
Please enter your name here