Dictionaries In Python

Dictionaries , unlike lists , store the objects in an unordered manner, meaning indexing cannot be performed in dictionaries. Dictionaries uses key-value pair to assign a value to a key and than later on that key can be used to get the specified value . Dictionaries used curly braces and colon to signify key and their associated value. It has the following syntax :

  • my_dict = {‘key1’ : ‘value1’ , ‘key2’ : ‘value2’}

You maybe thinking when to use list and when to use dictionaries. When you want to perform tasks like sorting , always use a list(since sorting cannot be performed in dictionaries) and when an object is to be associated to a particular key always use a dictionaries.

Let us take examples where we learn how to create dictionaries , grabbing a particular value from dictionaries and storing a dictionary and list within a dictionary.

my_dict = { 1 : 'a' , 2 : 'b' , 3 : 'c' }  print(my_dict)  #let us grab 'b' from dictionary  print(my_dict[2])

output:
{1: 'a', 2: 'b', 3: 'c'}  b

Let us take a example where we store a list and dictionary as a value (assigned to a key) and get values stored inside the lists and dictionaries using indexing.

my_dict = {'a' : [1,2,3] , 'b' : {1 : "abc" , 2 : "def"} , 'c' : "cat"}  #let us grab 2 from the list  print(my_dict['a'][1])  #let us grab "def" from dictionary  print(my_dict['b'][2])

output:
2  def 

So we know how to create a dictionary and call values from it . Now let us learn to create new key : value pair in dictionary and also reassign a different value to a key . ?

Creating new key : value pair is easy , simply assign a new key to a value and that key : value pair will become part of the dictionary. Note if a already used key is assigned a value , than this will overwrite the already existing value associated with the key. Let us understand this with a simple code.

my_dict = {1 : 'a' , 2 : 'b' , 3 : 'c'}  my_dict[4] = 'd'  print(my_dict)  #let us change the value associted with key 2 to 'f'  my_dict[2] = 'f'  print(my_dict)

output:
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}  {1: 'a', 2: 'f', 3: 'c', 4: 'd'}
Some common methods in dictionaries :

Keys() method :

The keys() method in dictionaries returns all the keys in a dictionaries in form of a list.

my_dict = {1 : 'a' , 2 : 'b' , 3 : 'c'}  print(my_dict.keys())

output:
[1, 2, 3] 

values() method :

The values() method in dictionaries returns all the values in a dictionary in form of a list .

my_dict = {1 : 'a' , 2 : 'b' , 3 : 'c'}  print(my_dict.values())

output:
['a','b','c'] 

items() method :

The items() method in dictionaries returns the key : value pair within a tuple( another popular data structure that will be discussed in later sections) enclosed by a list.

my_dict = {1 : 'a' , 2 : 'b' , 3 : 'c'}  print(my_dict.items())

output:
[(1, 'a'), (2, 'b'), (3, 'c')]