Python is a programming language with many tools and features. One such feature is the dictionary. A dictionary in Python is a collection of key-value pairs. The dictionary keys must be unique. The dictionary value may be of any type. In this blog post, we'll explore the dictionary in Python and learn how to use it.

Python Training Course

Learn Data Operations in PythonExplore Course
Python Training Course

What Is a Dictionary?

A dictionary is a kind of data structure that stores items in key-value pairs. A key is a unique identifier for an item, and a value is the data associated with that key. Dictionaries often store information such as words and definitions, but they can be used for much more. Dictionaries are mutable in Python, which means they can be changed after they are created. They are also unordered, indicating the items in a dictionary are not stored in any particular order.

Creating a Dictionary

Dictionaries are created using curly braces {}. The key is on the left side of the colon (:) and the value is on the right. A comma separates each key-value pair. Creating a Python dictionary is straightforward. Remember to use curly braces {} and separate each key-value pair with a comma.

You will use the built-in dictionary data type to create a Python dictionary. This type stores all kinds of data, from integers to strings to lists. The dictionary data type is similar to a list but uses keys instead of indexes to look up values.

You use the dict() function in Python to create a dictionary. This function takes two arguments:

The first argument is a list of keys.

The second argument is a list of values.

Check out the example of how to create a dictionary using the dict() function:

# empty dictionary

my_dict = {}

# dictionary with integer keys

my_dict = {1: 'apple', 2: 'ball'}

# dictionary with mixed keys

my_dict = {'name': 'John', 1: [2, 4, 3]}

# using dict()

my_dict = dict({1:'apple', 2:'ball'})

# from sequence having each item as a pair

my_dict = dict([(1,'apple'), (2,'ball')])

Data Science with Python

The Ultimate Ticket To Top Data Science Job RolesExplore Course
Data Science with Python

Complexities for Creating a Dictionary

The time complexity of a dictionary is O(len(dict)); because a dictionary must be created, the hash function must calculate the hash values for each element. O(N) is the space complexity required to create a dictionary.

Changing and Adding Elements to a Dictionary

In Python, dictionaries are mutable data structures that allow you to store key-value pairs. Dictionary can be created using the dict() constructor or curly braces' {}'. Once you have created a dictionary, you can add, remove, or update elements using the methods dict.update(), dict.pop(), and dict.popitem().

The `dict.update()` method is used to change an element in a dictionary. This method takes a key and a value as arguments and assigns the value to the key. It will be added if the key does not exist in the dictionary.

You can use the `dict.pop()` method to remove an element from a dictionary. This method takes a key value as an argument and removes the key-value pair from the dictionary. In case when key does not exist in the dictionary, `dict.pop()` will raise a `KeyError.`

The dict.popitem()` method is used to remove an arbitrary element from a dictionary, . This method removes a random key-value pair from the dictionary and returns it as a tuple. If the dictionary is empty, `dict.popitem()` will raise a `KeyError`.

Accessing Elements of a Dictionary

In Python, dictionaries are accessed by key, not by index. This means you can't access a dictionary element by using its position in the dictionary. Instead, you must use the dictionary key.

There are two ways to access a dictionary element in Python. The first is by using the get() method. This method takes two arguments: the dictionary key and a default value. If the key is in the dictionary, the get() method will return the value associated with that key. The get() method will return the default value if the key is not in the dictionary.

The second way to access a dictionary element is using the [] operator. This operator takes the dictionary key as an argument and returns the value associated with the key value. If the key value is not in the dictionary, the [] operator will raise a KeyError.

# get vs [] for retrieving elements

my_dict = {'name': 'Jack', 'age': 26}

# Output: Jack

print(my_dict['name'])

# Output: 26

print(my_dict.get('age'))

# Trying to access keys that don't exist throws an error

# Output None

print(my_dict.get('address'))

# KeyError

print(my_dict['address'])

Free Course: Python for Beginners

Master the fundamentals of PythonEnroll Now
Free Course: Python for Beginners

Methods

In Python, several built-in methods allow us to manipulate dictionaries. These methods are useful for adding, removing, and changing the values of dictionary keys. Dictionary methods are a powerful way to work with dictionaries. By understanding how these methods work, we can more effectively use dictionaries to store and manipulate data.

Method

Description

clear()

Removes all the elements from the dictionary

copy()

Returns a copy of the dictionary

get()

Returns specified key value

items()

Returns an index having a tuple for every key-value pair

keys()

Returns a list containing the dictionary's keys

pop()

Removes the element with the specified key

popitem()

Remove last inserted key-value pair

setdefault()

Returns specified key value. If a key value does not exist: insert the specified value of key

fromkeys()

Returns specified keys and values in dictionary

update()

Updates the specified key-value pairs in dictionary

values()

Returns values lists in the dictionary

Free Course: Programming with Python

Learn the Basics of Programming with PythonEnroll Now
Free Course: Programming with Python

Python Dictionary Comprehension

Dictionary comprehension is a feature that allows you to create a dictionary from a list or another dictionary in a single line of code. It is a very concise way of creating dictionaries and can be used to perform various operations on dictionaries. The expression of Dictionary comprehension is (key: value) followed by a for statement within the curly braces {}.

# Dictionary Comprehension

squares = {x: x*x for x in range(6)}

print(squares)

Dictionary Built-in Functions

Dictionaries have several built-in functions that allow you to perform various operations on them. all(), any(), len(), cmp(), sorted(), etc. are the most common dictionaries functions.

Function

Description

all()

The all() function in the python dictionary checks if all the keys in the dictionary have True as their values. If all the values are True, then it returns True. Otherwise, it returns False.

any()

The any() function on python dict checks if any of the values in the dict are True. If any of the values are True, it returns True, otherwise, it returns False.

cmp()

The cmp() function is used to compare two dictionaries by key. The function gives a negative value if the first dictionary is lesser than the second dictionary, a positive value if the first dictionary is greater than the second dictionary, and 0 if the two dictionaries are equal.

sorted()

This function is used to sort a dictionary in Python. The function takes two arguments: the dictionary to be sorted and the key on which the sorting will be based. The key can be a function, a list, or a tuple. The function returns a list of tuples, with each tuple consisting of the key and the value.

len()

It is a built-in function that returns the length of an object. It can be used on various objects such as strings, lists, dictionaries, etc.

Free Course: Python Libraries for Data Science

Learn the Basics of Python LibrariesEnroll Now
Free Course: Python Libraries for Data Science

Python Dictionary keys() Method

The keys() method in Python dictionary returns a view object that displays all the keys in the dictionary. View objects have some similar properties to the dictionary they are defined in. For example, you can iterate through a view object to print all the keys in the dictionary. It is possible to check if a key exists in a view object.

numbers = {1: 'one', 2: 'two', 3: 'three'}

# extracts the keys of the dictionary

dictionary keys = numbers.keys()

print(dictionaryKeys)

# Output: dict_keys([1, 2, 3])

Python Dictionary Values() Method

The values() method returns a view object that displays a list of all the values in the dictionary.

You can get the list of all the values in the dictionary using the values() method. The view object will reflect any changes made to the dictionary, so if you add or delete values from the dictionary, the view object will also update. The values() method differs from the keys() method because it doesn't take any arguments.

Check out the example on how to use the values() method in Python:

marks = {'Physics':67, 'Maths':87}

print(marks.values())

# Output: dict_values([67, 87])

Learn the essentials of object-oriented programming, web development with Django, and more with the Python Training Course. Enroll now!

Conclusion

Python is a great language that comes with many different features. It offers a structured code, making it easier to understand. With Python being one of the most prominent programming languages in today’s day and age, it is important to have a thorough understanding of this programming language. Simplilearn’s Python Certification Course is the best Python course to help you understand Python basics and other core concepts. It offers hands-on development experience and prepare you for an exciting career as a professional Python programmer.

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.