WORKING WITH PYTHON DICTIONARIES

avatar

image.png

Image Source

Dictionary is one of the major data types in python besides list, tuple, and set. While lists and tuples contain ordered collections of items, sets and dictionaries contain an unordered collection of items. Dictionaries store the value as a series of key-value pairs where the key is unique. And you can use this key to access the value. And also the key must be immutable such as tuples because tuples are immutable data types-once created, can't be changed or modified. Also, you can't store duplicate values inside the dictionary.

To identify a particular value of an element in a list, tuple, or set, you have to use an index number which is a numerical one. But there are many real-world problems where it is not convenient to access a particular element by a numerical value rather we want to use an alphabet to access value. For example, consider a phone book. Dictionaries can be used in the case of a phonebook where the name of the person is the key and their phone number is the value. In the case of airline reservation, you can notice the flight number is written as a mix of alphabet and number which is the key in our case and the same flight number can be used to access the flight information like capacity, route information, and so on.

Dictionaries are represented with curly braces and the sequence of key-value pairs are separated by comma. For example, this one is the simplest representation of python dictionary.

bike_dict = {
  "brand": "Apache",
  "model": "RTR 200",
  "Launched": 2018
}

You can use print(bike_dict) statement to print the dictionary as below:

image.png

In order to access the element of the dictionary, you need to use sets of square brackets [] and you should specify the key name inside for which you want to access the value for. For instance, lets access the bike model in our example above. So we will write print(bike_dict["model"]). If you run this program, it will print the bike model for you as below:

image.png

You can also add a new key-value pair to an existing dictionary. Just write the dictionary name followed by square brackets. Then write key name inside the brackets and then assign some value to that key. For example, lets add two new key-value pairs to the above dictionary which will include the mileage and the color.

bike_dict = {
  "brand": "Apache",
  "model": "RTR 200",
  "Launched": 2018
}

print("The original dictionary is:", bike_dict)

bike_dict["mileage"] = 50
bike_dict["color"] = "Matt Black"

print("\nThe new dictionary after addition of new key-value pair is:", bike_dict)

Running this program will give you following output:

image.png

You can also modify the value in dictionary. You need to write the name of the dictionary followed by a square bracket where you need to write the key for whose value you want to modify. Lets modify the launched date of our bike in the above dictionary.

bike_dict = {
  "brand": "Apache",
  "model": "RTR 200",
  "Launched": 2018
}

print("The original dictionary is:", bike_dict)

bike_dict["Launched"] = 2019


print("\nThe new dictionary after modification is:", bike_dict)

If you run this program, you will get the following output:

image.png

You can also delete an item from dictionary. Just use del keyword and then specify the dictionary name and the key inside a square bracket for which you want to delete the value for.

bike_dict = {
  "brand": "Apache",
  "model": "RTR 200",
  "Launched": 2018
}

print("The original dictionary is:", bike_dict)

del bike_dict["Launched"]


print("\nThe new dictionary after deletion is:", bike_dict)

Executing this code will give you this output:

image.png

Now lets see a code for looping through a key-value pair in dictionary. We will use a special in-built function called items() that will return a key-value pairs and we will store a key in variable "i" and its corresponding value in "j" in each iteration.

bike_dict = {
  "brand": "Apache",
  "model": "RTR 200",
  "Launched": 2018,
  "Mileage": 50,
  "Color": "Matt Black"
}

for i, j in bike_dict.items():
    print("Key:", i)
    print("Value:", j)
    print()

Now it will print a series of key and value upon execution as below:

image.png

Also we can use a list inside a dictionary. For example in the above code, the same bike can be found in other colors beside Matt Black. So we can specify the remaining color in the list as below:

bike_dict = {
  "brand": "Apache",
  "model": "RTR 200",
  "Launched": 2018,
  "Mileage": 50,
  "Color": ["Matt Black", "Red", "White", "Pink", "Shiny Black"]
}

for i, j in bike_dict.items():
    print("Key:", i)
    print("Value:", j)
    print()

If you run this program, you will get the following output:

image.png

Well can you use dictionary inside a dictionary. The answer to this one is yes. Python allows the concept of nested dictionary. But its not advisable to do this because your code can get longer and complicated. This one is a simple program demonstrating the simple concept of nested dictionary. We have a dictionary of Apache brand bike. The key of this dictionary is the model of bike itself (RTR 200V and RTR 180V) and the value of this key is again a dictionary consisting of different key-value pairs. At the end we have used a for loop logic to print out the statement describing each model of the brand with its mileage, color and launched date.

apache_bike = {
    'RTR 200V':{
        'mileage': 50,
        'launched': 2018,
        'color': "Black", 
    },
    'RTR 180V':{
        'mileage': 40,
        'launched': 2016,
        'color': "White", 
    }
}

for i,j in apache_bike.items():
    print(i +" has mileage of "+ str(j['mileage'])+", was launched in "+str(j['launched'])+" and is found in "+j['color']+ " color")
    print()

If you run this program then you will get the following output:

image.png

You can try practicing and running this code online here.



0
0
0.000
2 comments
avatar

I find dictionaries really useful, i didnt realise you can have one inside another. Great post keep them coming.

0
0
0.000
avatar

Sure. Appreciate your time for looking into my post.

0
0
0.000