Friday, 16 August 2019

Python list of dictionaries | Python 3 Dictionaries with example

Python list of dictionaries | Python 3 Dictionaries with example


Dictionaries are simply another type of collection in python, but with a twist. Dictionaries in python have a “key” and a “value of that key”. It is a collection of some key-value pairs.

Just like, In English dictionaries you can search for a word’s meaning, because for each word, there is a meaning associated with it. In the same manner, python dictionaries have some keys and associated values.

Dictionaries are containers that associate keys to values. This is similar to lists but in lists you must remember the index value of an element from the list, in case of dictionaries you will have to know the key to find in the dictionaries.

Dictionaries are mutable, unordered collections with elements in the form of a key: value pairs that associate keys to values.


Creating a Dictionary

To create a dictionary, you need to include the key: value pairs in curly braces.

Syntax:

<dictionary-name>= {<key>:<value>, <key>:<value>….}

For example:

We make a dictionary by the name teachers that stores the names of teachers as Keys and the subjects being taught by them as values of respective keys.

Teachers= {“Dimple”: “Computer”,” Karan”:” Maths”,” Anu”:” History”}

Or

Dict= {}         #It is an empty dictionary with no elements.

  • The curly brackets mark the beginning and the end of the dictionary.
  • Each entry (Key: value) consists of a pair separated by a colon’:’.
  • The key-value pairs are separated by commas (,).
  • Dictionaries are also called associative arrays or mappings or hashes.


As we know dictionaries are mutable but keys of a dictionary must be of immutable types. If you tried to assign a key with mutable type, unshushable type error would be raised because python dictionaries do not allow this.

Accessing Elements of a Dictionary

While accessing elements from a dictionary, you need the key. While in lists, the elements are accessed through their index; in dictionaries, the elements are accessed through the keys defined in the key: value pairs.

Syntax:

<dictionary-name>[<key>]

For example:

Teachers= {“Dimple”: “Computer”,” Karan”:” Maths”,” Anu”:” History”}

Teachers [“Karan”]

Output:

Maths

Similarly, you can write as

print (“Karan teaches”, Teachers[‘Karan’])
            
             Output: Karan teaches Maths

Screenshot:

How to create dictionary in python3


A dictionary operation that takes a key and finds the corresponding value is called lookup.

Screenshot:

Display dictionary data in python3

Example of dictionay in python3


While giving key inside square brackets gives you access only to the value corresponding the mentioned key, mentioning the dictionary names without any square brackets prints/displays the entire contents of the dictionary.
We can say that key order is not guaranteed in python. This is because in Python dictionaries, the elements (key: value) are unordered; one cannot access element as per specific order. The only way to access a value is through key. Thus, we can say that keys act like indexes to access values from a dictionary.

Also, attempting to access a key that does not exist causes an error.

Traversing a Dictionary

Traversal of a collection means accessing and processing each element of it. Thus, traversing a dictionary also means the same and same is the tool for it i.e. the Python loops.
The for loop makes it easy to traverse or loop over the items in a dictionary.

Syntax:

for <item> in <Dictionary>:
process each item here

The loop variable <item> will be assigned the keys of <Dictionary> one by one, they are assigned indexes of strings or lists while traversing them, which you can use inside the body of the for loop.

For example:

Question: Write a program to create a phone dictionary for all your friends and print it.

Answer:

PhoneDict= {“Madhav”: “7865678986”,” Harpreet”: “765434566”,” Anil”: “5676655444”,”                               Preethi”: “8976654433”}

for name in PhoneDict:

                print (name,”:”, PhoneDict [name])

Screenshot:

Example of dictionary using for loop




You can use a for loop to get hold of indexes or keys and then print or access corresponding values inside the loop-body.

No comments:

Post a Comment

Recent Post

Python Project | Banking System | Project on Banking System using python

  PYTHON PROJECT Banking System import csv import pandas as pd import matplotlib.pyplot as plt import sys import datetime found=False def ne...