A Dictionary in python is key-value pairs separated by comma. Dictionary is defined using curly braces { }.
Important thing to remember is, the keys must be immutable and values can be any valid python object.
Hence, keys could be a number, string, tuple etc. and values could be number, string, tuple, lists, dictionaries etc.
1 2 3 4 5 6 7 8 9 10 |
# Creating a simple dictionary dict1={101:'ram', 102:'sham', 103:'ravi'} # printing the whole dictionary print(dict1) # accessing a value using its key dict1[103] |
Sample Output:

A Dictionary can contain a dictionary inside it
Python dictionaries are one of the most complex data structures. It can contain any valid python object as values. Hence, it can contain a dictionary only as values, not as a key because, the keys of a dictionary must be immutable data types.
1 2 3 4 5 6 7 8 |
# A Dictionary can contain a dictionary inside it only as Value dict1={101:'ram',102:'sham',103: {301:10, 302:20}} # printing values of the dictionary print(dict1) # accessing the dictionary inside dictionary dict1[103][301] |
Sample Output:

Common Dictionary commands
Whenever you create a new object in python, there are a set of pre-built methods which gets assigned to it and are available to use. You can check these list of functions using a dot(.) + tab button.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# Common dictionary commands # Creating a simple dictionary dict1={101:'ram', 102:'sham', 103:'ravi'} # Extracting only the keys print('All the keys in the dictionary:',dict1.keys()) # Extracting only the values print('All the values in the dictionary:',dict1.values()) # Extracting only the values print('All the key-value pairs in the dictionary') print(dict1.items()) # Get the value for a particular key print('Value for key 101:',dict1.get(101)) # Get the values for multiple keys # No pre-built function for it, loop is needed key_set=[101,102] for k in key_set: print(dict1.get(k)) # Adding a new entry to the dictionary # Keys can be of different datatypes dict1[300]='hello' dict1[302]=[2,3,4] dict1['ID_01']='test item' print(dict1) # Deleting an item from the dictionary based on keys dict1.pop(300) print('dictionary after removing value of key 300:', dict1.items()) # Deleting the last item from the dictionary dict1.popitem() print('dictionary after removing last key-value pair:', dict1.items()) |
Sample Output:
