Skip to content

Python Dictionary – An Intro for Beginners

Python Dictionary

Python Dictionary is used to store multiple items in key:value pair in a single variable . Python Dictionary is surrounded by curly braces ({}) . Python provides total 4 built-in data types to store collection of data of which one is Dictionary . The other data types are List , Set and Tuple .

How to create a Dictionary in Python ?

There are multiple ways to create a Python Dictionary –

To check if it is a dictionary or not we can use type() function .

# Creating a dictionary in Python

# Using curly braces ({})
dictionary_from_bracket = {"Rajkumar":1,"apple":2,True:3,1:4,2.5:5,10:6}
print(dictionary_from_bracket)
# checking the type
print("type of dictionary_from_bracket",type(dictionary_from_bracket))

# using dict() function
dictionary_from_function = dict((("Rajkumar",1),("apple",2),(True,3),(1,4),(2.5,5),(10,6)))
print(dictionary_from_function)
# checking the type
print("type of dictionary_from_function",type(dictionary_from_function))

# using dictionary comprehension
dictionary_from_comprehension  = {item:(item+5) for item in range(5)}
print(dictionary_from_comprehension)
# checking the type
print("type of dictionary_from_comprehension",type(dictionary_from_comprehension))
{'Rajkumar': 1, 'apple': 2, True: 4, 2.5: 5, 10: 6}
type of dictionary_from_bracket <class 'dict'>
{'Rajkumar': 1, 'apple': 2, True: 4, 2.5: 5, 10: 6}
type of dictionary_from_function <class 'dict'>
{0: 5, 1: 6, 2: 7, 3: 8, 4: 9}
type of dictionary_from_comprehension <class 'dict'>
  • In the above code we have created dictionary using various ways
  • First we have created dictionary using curly braces ({}) . Then we have printed the dictionary and also its type .
  • Second we have created dictionary using dict() . Then we have printed the dictionary and also its type .
  • Third we have created dictionary using dictionary comprehension . Then we have printed the dictionary and also its type .
  • From the output we can see that in every case type is dictionary .

Note :

Dictionary items are separated by comma (,) and it can be of any type as we have seen in the previous code .

Characteristics of a Dictionary in Python

Python dictionary is unindexed , ordered and mutable(changeable) collection of items . Dictionary key can not be duplicate but we can use duplicate values as dictionary value .

Python Dictionary is unindexed | How to access value in dictionary Python

Python Dictionary is unindexed it means we can not access dictionary items using its index . If we try to do that it will raise KeyError .

Example 1:

mydictionary = {"Rajkumar":1,"apple":2,True:3,"Apple":4,2.5:5,None:6}
print(mydictionary[2])
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
C:\Users\RAJKUM~1\AppData\Local\Temp/ipykernel_8092/535005601.py in <module>
      1 mydictionary = {"Rajkumar":1,"apple":2,True:3,"Apple":4,2.5:5,None:6}
----> 2 print(mydictionary[2])

KeyError: 2

In the above code when we have tried to access dictionary items using its index it has raised an error . Actually when we have written mydictionary[2] program has checked whether 2 is in dictionary key or not . As 2 is not a dictionary key so the program raised an KeyError .

So if we give valid dictionary key between the square bracket then the program should not give any error . Now we will see how to access value in dictionary Python using dictionary key with examples –

Example 2:

# Declaring a dictionary
mydictionary = {"Rajkumar":1, "apple":2,True:3,"Apple":4,2.5:5,None:6}

# accessing value of Rajkumar key
print(mydictionary["Rajkumar"])

# accessing value of True key
print(mydictionary[True])
1
3
  • In the above code first we have declared a dictionary named mydictionary as {"Rajkumar":1, "apple":2, True:3, "Apple":4, 2.5:5, None:6} which have 6 key "Rajkumar" , "apple" , True , "Apple" , 2.5 , None whose corresponding values are 1 , 2 , 3 , 4 , 5 , 6 .
  • After that we have printed value of "Rajkumar" key which printed 1 in the output .
  • Then we have printed value of True key which printed 3 in the output .

Python Dictionary is ordered

Dictionary items are ordered it means that it maintains a defined order and we can not change it .

Note :

Before Python version 3.7 Dictionary items were unordered .

Python Dictionary is mutable | How to update a Dictionary in Python ?

Python dictionary is mutable it means we can change , delete and add items in the dictionary .

Example 1:

# Declaring a dictionary
mydictionary = {"Rajkumar":1,"apple":2,True:3,"Apple":4,2.5:5,None:6}

# printing the dictionary
print(mydictionary)

# updating the dictionary using its key
mydictionary["Rajkumar"]=11

# printing the updated dictionary
print(mydictionary)
{'Rajkumar': 1, 'apple': 2, True: 3, 'Apple': 4, 2.5: 5, None: 6}
{'Rajkumar': 11, 'apple': 2, True: 3, 'Apple': 4, 2.5: 5, None: 6}
  • In the above code first we have declared a dictionary then we have printed the dictionary .
  • Then we have changed the value of "Rajkumar" key with 11 .
  • After that we have printed the new dictionary .

Python Dictionary does not allow duplicate key

Previously we have seen that we can access any value of a dictionary using its key . So if a Python dictionary has more than one key with same name , when we want to access value using key, Python will not understand value of which key we want to access . For this reason key in Python dictionary can not be duplicate .

How to delete a Dictionary in Python ?

We can delete a dictionary in Python using del keyword . But if we want to access the dictionary after deleting it using del keyword it will raise a NameError .

Example:

# Declaring a dictionary
mydictionary = {"Rajkumar":1,"apple":2,True:3,"Apple":4,2.5:5,None:6}

# printing the dictionary before deleting
print(mydictionary)

# delete the dictionary
del mydictionary

# printing the dictionary after deleting
print(mydictionary)
{'Rajkumar': 1, 'apple': 2, True: 3, 'Apple': 4, 2.5: 5, None: 6}
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
C:\Users\RAJKUM~1\AppData\Local\Temp/ipykernel_14124/2734959277.py in <module>
      9 
     10 # # printing the dictionary after deleting
---> 11 print(mydictionary)

NameError: name 'mydictionary' is not defined

Iterating a Dictionary in Python

We can iterate a dictionary in Python using for-loop and while-loop .

Example 1:

# for loop with dictionary as iterator
mydictionary = {"Rajkumar":1,"apple":2,True:3,"Apple":4,2.5:5,None:6}
for element in mydictionary:
    print(element)
Rajkumar
apple
True
Apple
2.5
None

In the above code we have iterated all element from mydictionary using for-loop . By default it will print all the key . To print the value we need to write mydictionary[element] instead of element in 4th line .

Example 2:

# python while loop with dictionary datatype
mydictionary = {"Rajkumar":1,"apple":2,True:3,"Apple":4,2.5:5,None:6}
number=0
while number < len(mydictionary):
    print(list(mydictionary.keys())[number])
    number+=1
Rajkumar
apple
True
Apple
2.5
None

In the above code we have iterated all keys from mydictionary using while-loop . Here using list(mydictionary.keys()) we have converted {"Rajkumar":1, "apple":2, True:3, "Apple":4, 2.5:5, None:6} to ["Rajkumar","apple",True,"Apple",2.5,None]

To know about len() function click here .

Nested Dictionary in Python

When we use dictionary inside a dictionary then it is called Nested dictionary . Earlier we have seen that dictionary items can be of any datatype . So dictionary item can be a dictionary .

Example :

# nested dictionary in python
mydictionary = {"Rajkumar":1,"apple":2,True:3,"Apple":{"mango":1,"banana":2},2.5:5,None:6}
print(mydictionary)
{'Rajkumar': 1, 'apple': 2, True: 3, 'Apple': {'mango': 1, 'banana': 2}, 2.5: 5, None: 6}

In the above code we have seen that Python accepts a dictionary as dictionary value .

Thank you for reading this Article . If You enjoy it Please Share the article . If you want to say something Please Comment .

Leave a Reply