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 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))
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 None print(fruits.get(3)) # Raises KeyError since 3 is not a key in fruits dictionary print(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 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))
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
RELATED TAGS
CONTRIBUTOR
View all Courses