top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-

All about Dictionaries in Python - Basics to Dictionary Comprehensions


Before we start learning about Dictionaries, let's take a look at the basic data types and data structures in Python.

We have Integers, Floating point numbers, Boolean and String type as the basic data types.


Lists, Tuples, Dictionaries and Sets are the data structures in Python . Data structures are collection of objects regardless of the datatype.



What are Dictionaries ?


Dictionaries are ordered mappings for storing objects (In Earlier versions of Python before 3.7 , Dictionaries were unordered)

Objects are stored in the form of key, value pairs and curly brackets {} are used to store the objects.

Dictionaries are changeable, which means that more key value pairs can be added or removed after creating a dictionary.


Creating a dictionary


Here in the below example, dict1 is a variable which is a dictionary type where 'CA', 'NJ 'and 'MN' are the keys and the corresponding capital cities are the values associated with the keys. They are separated with a colon and enclosed within curly braces.







How to create an empty dictionary ?


We can declare a dictionary by enclosing key:value pairs within the curly braces

dict1 = {} # Empty dictionary

dict2 = {'Fruit':'Apple'} # Dictionary with initial values


Accessing the keys and values in a dictionary


  1. We can access directly from the dictionary itself by using the key() and values() methods on the variable.










2. We can also assign it to a variable explicitly to get the keys and values.

The result is a new type called dict_keys and dict_values which are displayed as Lists but are not exactly the same. If we want to re-use these dict_keys and dict_values as lists then we need to typecast them into List type.

















3. We can access individual items in a dictionary using the get() method






Changing items in a dictionary


  1. Referring to the key - Can change one value at a time, specifying key should be enough to

    change the value


2. Using the update() method - Can change one value at a time but both keys and values must be specified



3. Using zip() method : This method aggregates the iterable and combines them into a tuple form - Can change the entire list of values.

In the below example, we are trying to convert the dict1.keys() into a list and then zipping it with list1 and then typecasting it back to a dictionary.


Adding items to a dictionary


  1. We can add items to a dictionary by creating a new key and assigning a value to it.



2. Using update() method to add items to a dictionary



Removing items from a Dictionary

There are multiple ways to remove items from a dictionary using some methods. We can also delete a dictionary as a whole. Let us see the different ways below.


  1. Using the pop() method : The pop() method pops out the key: value pair for the specified key from the dictionary.


2. Using the popitem() method : The popitem() method removes the last inserted item/ key: value pair from the dictionary


3. Using the del keyword : The del key word removes the item/ key: value pair from the dictionary

provided the key is specified . This is slightly different from the pop method.


4. Using the clear() method : The clear() method completely empties the dictionary


Copying Dictionaries


There are 2 ways to copy dictionaries.


  1. Using the copy() method

dict1 = { 1 : 'apple', 2 : 'banana' }

dict_copy = dict1.copy()

print(dict_copy)

This copy() method will copy the items in dict1 to dict_copy


2. Using the dict() method : This method can also be referred to as type casting a variable to a dictionary

dict1 = { 1: 'apple', 2: 'banana' }

dict_copy = dict(dict1)


Referencing to a dictionary

When we try to directly assign dict1 = dict 2, dict 2 will also be the same as dict 1 but it cannot be considered as copying dictionaries. dict2 is actually referencing to dict1. That means that any changes made to dict 1 will be applied to dict2 also and vice versa. In the case of copying one dictionary to other, it actually creates 2 different dictionaries so if you change one, the change would not reflect in the other.




Merging Dictionaries in Python


There are multiple ways to merge dictionaries.


  1. Using update() method and a function


2. Using a function and kwargs(**) operator (unpacking operator)

The syntax **kwargs in function definition is used to pass a variable length argument list.












3. Using | operator and a function



4. Using a function, for loop and keys() method

In the below code, we are trying to assign the keys of dict2 as a key to dict1 to add the key value pairs into dict1



5. Using a function, items() method and dict() constructor



6. Using a function, reduce() function from functools module and update() methods



List of methods in Dictionaries

Below are a list of methods that can be used on dictionaries. We have already covered most of them in the examples above while accessing, adding, changing, copying, merging and removing dictionaries. Please refer to those examples on how to use the methods and you can try some on your own as well.


clear() fromkeys() pop() dict()

copy() keys() popitem() reduce()

get() values() setdefault()

items() update()



Looping through Dictionaries

Suppose we want to print or create a list of all the keys or all the values of a dictionary, then we need to loop through the dictionary. We can achieve that by using a for loop. Let us see few examples below on how to loop through a dictionary and how to apply the methods to access the keys and values in a dictionary.


To get/print all the keys in a dictionary










To get/print all the values in a dictionary











Using keys() method in a for loop to get/print the keys in a dictionary










Using the values() method in a for loop to get/print the values in a dictionary




Note that we are not using the dict1[a] to print the values here





Using the items() method in a for loop to get/print both keys and values in a dictionary












Nested Dictionaries

If a dictionary contains another dictionary in its values then those are termed as nester dictionaries.

For example:

dict1 = { 'John' : { 'Math':98, 'Science':96, 'English' :92 } ,

'Sarah' : { 'Math':90, 'Science':98, 'English' :88 } }


To access John's marks in Science subject :

print( dict1['John']['Science'])

To access Sarah's marks in English subject :

print(dict1['Sarah']['English'])


To access and print all the items in the nested dictionary:




Dictionary Comprehensions

Dictionary Comprehension is a concise way of creating a dictionary using simple expressions including an iterable in a single line of code.

Syntax :

{ key expression : value expression for item in iterable }

Let us see an example to create squares using a for loop and using dictionary compreshension



Incase we need to generate based on a certain condition like for only odd numbers, we can include that as well in the same line of code like this -

squares = { x : x**2 for x in range(5) if x%2 != 0}



Example : Given a dictionary dict1 = { a : 1 , b : 2 , c : 3 , d : 4 , e : 5 , f : 6 }. Create a dictionary using dictionary comprehensions where all the keys should be in uppercase and all the values should meet below criteria.

if values of dict 1 > 3 then add 10 else add 20.

Solution:

new_dict = { k.upper() : v + 10 if v > 3 else v + 20 for k,v in dict1.items() }


Conclusion:

Dictionaries in Python are powerful and versatile data structures that allow you to store and manage data efficiently. Overall, Python dictionaries are essential tools for developers, providing an intuitive way to manage complex data structures while maintaining efficiency and readability in code. Their integration with various libraries and frameworks further enhances their usability across different domains.


Thank you !


14 views0 comments

Recent Posts

See All

Kommentare

Mit 0 von 5 Sternen bewertet.
Noch keine Ratings

Die Kommentarfunktion wurde abgeschaltet.
bottom of page