Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
dictionary
communitycreator

What are python dictionaries?

Gutha Vamsi Krishna

A Python dictionary is an unordered collection of items where every item is a key/value pair.

Creating a dictionary

  • To create a python dictionary, simply place itemskey:value/pairs in curly brackets {}, separated by commas.

  • Keys must be immutable for an item in a dictionary, whereas values can be of any datatypes.

Below are different ways to create a dictionary.

# empty dictionary
empty_dict = {}
print("Empty dictionary --> "+ str(empty_dict))

# dictionary with items
fruits = {1:"Apple",2:"Orange"}
print("fruits dictionary --> "+ str(fruits))

# using built in dict() function
pets = dict({1:"Cat",2:"Dog"})
print("pets dictionary --> "+ str(pets))

Accessing elements from a dictionary

Python dictionary uses Keys to access items such as:

  • Square brackets []
  • The get() method

Interpreter may throw KeyError, if a key is not found in dictionary when we use square brackets []. However, the get() method returns None.

It’s always safer to use the get() method.

fruits = {1:"Apple",2:"Orange"}
print(fruits[1])
print(fruits.get(1))

# returns None
print(fruits.get(3))

# Raises KeyError since 3 is not a key in fruits dictionary
print(fruits[3])

Adding or removing items

We can add new items or change the value of existing items using the assignment = operator.

Use the pop() method to remove an item from a dictionary. It takes key as a parameter and returns the value of the item that is removed.

fruits = {1:"Apple",2:"Orange"}
print("Original fruits dict --> "+str(fruits))

# add new item
fruits[3] = "Banana"
print("Added 'Banana' to fruits dict --> "+str(fruits))


# change value of an item
fruits[2] = "Grapes"
print("Change Value at index 2 in fruits dict --> "+str(fruits))

# removes item and returns it
fruits.pop(1)
print("Remove element at index 1 fruits dict --> "+str(fruits))

When to use python dictionaries

We have other data structures like List, Set etc., in Python. Therefore, it is important to know when to use dictionaries.

  • Python dictionaries are optimized versions of HashMap.
  • HashMaps are developed for faster lookups.
  • Use Python dictionaries when there is a need to search elements faster.

Time complexity to set, get and delete an item in dictionary is O(n)O(n)

RELATED TAGS

python
dictionary
communitycreator
RELATED COURSES

View all Courses

Keep Exploring