A Python dictionary is an unordered collection of items where every item is a key/value
pair.
To create a python dictionary, simply place value/pairs
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 dictionaryempty_dict = {}print("Empty dictionary --> "+ str(empty_dict))# dictionary with itemsfruits = {1:"Apple",2:"Orange"}print("fruits dictionary --> "+ str(fruits))# using built in dict() functionpets = dict({1:"Cat",2:"Dog"})print("pets dictionary --> "+ str(pets))
Python dictionary uses Keys
to access items such as:
[]
get()
methodInterpreter may throw
KeyError
, if a key is not found in dictionary when we use square brackets[]
. However, theget()
method returnsNone
.
It’s always safer to use the get()
method.
fruits = {1:"Apple",2:"Orange"}print(fruits[1])print(fruits.get(1))# returns Noneprint(fruits.get(3))# Raises KeyError since 3 is not a key in fruits dictionaryprint(fruits[3])
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 itemfruits[3] = "Banana"print("Added 'Banana' to fruits dict --> "+str(fruits))# change value of an itemfruits[2] = "Grapes"print("Change Value at index 2 in fruits dict --> "+str(fruits))# removes item and returns itfruits.pop(1)print("Remove element at index 1 fruits dict --> "+str(fruits))
We have other data structures like List
, Set
etc., in Python. Therefore, it is important to know when to use dictionaries.
Time complexity to set, get and delete an item in dictionary is