Register Login

Dictionary in Python

Updated Jun 01, 2023

Python provides basic data structures like list, tuple, dictionary, and set, which have unique characteristics. Users can use these data structures to organize, manage and store data in the way they specify and the type of data structure.

In Python, data structures are mainly two types, mutable and immutable. Mutable data structures provide the ability to change the value of the elements. And immutable is just the opposite and is easily accessible. From this article, you will get to know the Python dictionary and its related topics.

What is a Dictionary?

A dictionary is a data structure that stores key-value paired elements where these keys must be a unique identifier. Dictionaries are mutable, and users can change the values of the elements after they create them.

Dictionaries do not store data elements in an ordered manner, i.e., it does not hold elements in specific orders.

Syntax:

d = {1: 'A', 2: 'B', 3: 'C'}

where d is the variable for declaring a dictionary, and it stores three key-value pairs.

How to create a dictionary?

Users can create dictionaries using curly brackets {}. We set the key on the left side of the colon : and the value on the right side and then use a comma as an operator to separate the key-value pairs.

Creating a Python dictionary is as easy as you think. In the following code snippet, users will see how easily we initialized a Python dictionary with keys and values.

Code Snippet:

dict1 = {}
dict2 = {1: 'A', 2: 'B'}
dict3 = {'A': 'B', 1: [4.5, 23.876, 45.9867]}
dict4 = dict({1:'a', 2:'b'})
dict5 = dict([(1.1,'A'), (2.2,'B')])
print (dict1)
print (dict2)
print (dict3)
print (dict4)
print (dict5)

Output:

Explanation:

In this example, we have initialized five different dictionaries having distinct values. Users can use the built-in dictionary data type for creating a Python dictionary. Using this data type, users can store any type of data, like integers, floating points, strings, lists, etc.

The dictionary data type functions as the Python list but has unique keys instead of indexes to serve values.

Using the dict() function to create a dictionary

Here, we will use the dict() function to create a dictionary:

a = dict(One = 1, Two = 2)
print(a)

Output:

Explanation:

One disadvantage of using the dict() function is users cannot initialize the key as a number (integer or decimal). It will return an error, "a = dict(1= "One", 2= "Two")," i.e. if we initialize a = dict(1= "One", 2= "Two").

Time complexities for creating a dictionary

The time complexity of a Python dictionary is O(len(dict)); since users need to create a dictionary must, and then the hash function will calculate the hash values for every element. O(N) represents the space complexity required for creating the Python dictionary.

How to add elements to a dictionary?

There are various ways to add elements to a Python dictionary. Users can add one value at a time to the Python dictionary by specifying the value with a unique key, i.e., Dict[Key] = 'Value.' Also, users can update the current value in the Python Dictionary using the built-in update() method.

In the dictionary, users can also add nested values that benefit users in several ways. But if a key-value pair gets repeated, the Python interpreter accepts only one.

Code Snippet:

demo = {}
print("It is an empty dictionary: ")
print(demo)
# Here, we add elements one at a time to the dictionary
demo[1.1] = 'A'
demo[2.1] = 'B'
demo[3.1] = 'C'
print("\n We created a final Python dictionary using these three elements: ")
print(demo)

# Here, we add several values to a single key
demo['keys'] = 324.4, 53.6, 87.932
print("\n We created a dictionary by adding three elements to the same key: ")
print(demo)

# We updated the existing Key's Value
demo[4.1] = 'Hello PYTHON'
print("\n This is the updated key-value: ")
print(demo)

# Lastly, we add a nested key-value pair into the Dictionary
demo[5.1] = {'Nest': {1: 'x', 2: 'y'}}
print("\n We added the nested key: ")
print(demo)

Output:

Explanation:

As you can see, this example has used five different approaches to create and add key-value pairs to the Python dictionary "demo." We have explained through Python comments what we have done in each dictionary, and the last dictionary has all the key-value pairs we have declared from the first one.

Time complexity if adding key-value in Python dictionary

Time complexity is O(1)/O(n), and Space complexity is O(1).

What is a nested dictionary?

A nested dictionary is a Python dictionary that exists inside a parent dictionary. In other words, a nested dictionary defines the collection of many sub-dictionaries inside a single dictionary.

For example:

demo = {1.0: 'A', 2.0: 'B', 3.0: {'x': 'This', 'y': 'is', 'z': 'Dictionary'}}
print(demo)

Output:

Explanation:

Here, we used a "demo" dictionary, which has three key-value pairs, where the last key, i.e., "3.0," has a nested dictionary of three key-value pairs.

How to access elements from a dictionary?

To access the elements of a Python dictionary, users have to refer to the key of that pair. Like other data structures, here, users will use a key as the index to access elements. Two ways that we can use to access the elements are using the get() method and the [] operator.

Method 1: Using the get() method

The get() method will help users get the value against the key; which they select. If the key-value pair does not exist, it will return none.

Syntax:

Dict.get(key, default=None)

Parameters used:

  • Key – This parameter specifies the key name of the element users select to return the value from
  • Value – It is an optional parameter and specifies the value the method will return if it does not find the key. The default value is None.

Method 2: Using the [] operator

The indexing operator [] can get the value at the specified index or key in dictionaries. The indexing operator accepts the key as the argument and returns the value against that key. If it does not find the key-value pair in the dictionary, it will throw a KeyError.

Code Snippet:

demo = {'name': 'ABC', 'Salary': 65000, 'Company': 'XYZ'}
print(demo['name'])
print(demo.get('Salary'))
print(demo.get('phone number'))
print(demo['Company'])

Output:

Explanation:

Look at the output and see the get() method has returned the value against the key, and None for the key does not exist in the dictionary. Also, we used the indexing operator that returns the value of the specified key.

How to delete elements from a dictionary?

There are several ways to delete an element from the dictionary, and these are the del keyword, pop() method, items() + dict comprehension, the Python clear() method, etc.

Code Snippet:

demo = {'Name': 'ABC', 'Salary': 65000, 'Company': 'XYZ'}
del demo['Name']
print(demo)
b = demo.clear()
print(b)

Output:

Explanation:

For instance, we used the clear() and "de" keyword to see how to delete elements from a dictionary. The clear() method returned None after removing all the dictionary elements; at a time, the del keyword deleted the specific key-value pair.

Various methods used in Python dictionary

  • dic.clear() – Using this method, users can delete all the elements from the dictionary
  • dict.copy() – This method returns a copy of the current dictionary
  • dict.get(key, default = "None") – Users can use this method to retrieve the value of a specified key
  • dict.items() – Using this method, users can get the list containing a tuple every each key-value pair
  • dict.keys() – Using this method, users can get the list that contains all the keys of the dictionary
  • dict.update(dict2) – This method will return the updated dictionary with specified key-value pairs
  • dict.values() – Users can use this method to return the list of all the values of the dictionary
  • pop() – This method will delete the key-value pair that users will specify as the key
  • popItem() – This method also deletes the last inserted key-value pair
  • dict.setdefault(key,default= "None") – Using this method, if users have not selected the key in the dictionary, they can set the key to the default value
  • dict.has_key(key) – This method searches for the key and returns true if it finds the specified key in the dictionary
  • dict.get(key, default = "None") – Users can use this method to get the value selected for the assigned key.

Code Snippet:

a = {1.0: "We,", 2.0: "are", 3.0: "using", 4.0: "dictionary", 5.0: "methods"}
x = {1.0: "We,", 2.0: "are", 3.0: "using", 4.0: "dictionary", 5.0: "methods"}
# coping dictionary
b = a.copy()
print(b)
# deleting all the elements
a.clear()
print(a)

# accessing the first element
print(b.get(1))

# items() method
print(b.items())

# getting only the keys
print(b.keys())

# Removing the third element
b.pop(3)
print(b)

# popitem() method
x.popitem()
print(x)

# updating the dictionary
b.update({3.0: "."})
print(b)

# fetching only the values
print(b.values())

Output:

Functions used in Python Dictionary

  • all() – Using the all() function, users can check if all the keys in the dictionary are True and match their values in the Python dictionary. If all the elements in the iterable are True, it returns True. Else, it returns False.
  • any() – Users can use the any() function on the Python dictionary to check if any of the values in the dict is True. If it finds any of the values is True, it returns True. Else, it returns False.
  • cmp() – Users can use the cmp() function to compare two dictionaries using the keys. The function returns a negative value if the first dictionary is less than the second. It returns a positive value if vice versa and zero if it finds the two dictionaries are equal.
  • sorted() – Using this function, users can sort a dictionary. This Python function accepts two arguments. i.e., the dictionary users want to sort and the key on which the function will base the technique. The key can take a list, a Python function, or a tuple.
  • len() – Users can get the length of the Python dictionary using this built-in function. Other than a dictionary, users can also use it on different data structures such as strings, lists, tuples, etc.

Conclusion

Understanding the Python language and grabbing an out-and-out knowledge of the Python dictionary is essential. There are countless applications of a Python dictionary, and users can manipulate a dictionary as per requirement using the different methods and functions Python provides.

We hope this article has given a crisp idea of all the topics related to the Python dictionary and the associated operations with this mutable data structure.


×