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.

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')])

Image Reference

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'])​

Image Reference

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

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.

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])
​

Image Reference

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])
​

Image Reference

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 Post Graduate Program in Full Stack Web Development 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.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 17 Jun, 2024

6 Months$ 8,000
Full Stack Developer - MERN Stack

Cohort Starts: 30 Apr, 2024

6 Months$ 1,449
Automation Test Engineer

Cohort Starts: 1 May, 2024

11 Months$ 1,499
Full Stack Java Developer

Cohort Starts: 14 May, 2024

6 Months$ 1,449

Get Free Certifications with free video courses

  • Python for Beginners

    Software Development

    Python for Beginners

    10 hours4.5271.5K learners
  • Python Programming 101: Beginner’s guide

    Software Development

    Python Programming 101: Beginner’s guide

    1 hours4.51.5K learners
prevNext

Learn from Industry Experts with free Masterclasses

  • Prepare for Digital Transformation with Purdue University

    Business and Leadership

    Prepare for Digital Transformation with Purdue University

    11th Jan, Wednesday9:00 PM IST
  • Program Preview: Post Graduate Program in Digital Transformation

    Career Fast-track

    Program Preview: Post Graduate Program in Digital Transformation

    20th Jul, Wednesday9:00 PM IST
  • Expert Masterclass: Design Thinking for Digital Transformation

    Career Fast-track

    Expert Masterclass: Design Thinking for Digital Transformation

    31st Mar, Thursday9:00 PM IST
prevNext