Python Basic Tutorials

Python is a high level general purpose programming language which has a clear/easy learning curve. Python programming language is massively used in various domains like Artificial Intelligence, Data Science, Web Development, Utilities Tools and Scripts and many more

Python is a Programming language, and the default Python we use is written in C programming language which is also referred to as CPython (Python implementation in C). There are various implementation of Python Programming language i.e Jython(in JAVA), Skulpt(in JS) e.t.c

To make everything easy: We refer CPython as Python

Python Dictionary

Dictionary in python is an optimized data structure with the collection of key-value pairs. Dictionary in Python consists of pair of things named keys and values. The curly braces {} are used to denote the dictionaries.

Example

we will create a dictionary named "food_details" which stores the basic information such as name, price, and quantity of certain food.


food_details = {
    "name": "Pizza",
    "price": 500,
    "quantity": 5
}

Now that we've added one food item, we can look them up in the following way.


>>>food_details["name"]
   "Pizza"

Display the price of food item


>>> food_details["price"]
    100

Adding some more quantity to the existing dictionary


>>> food_details["quantity"] = food_details["quantity"] + 15

Display the quantity of food_items


>>>food_details["quantity"]
   20
Adding more key-value pairs to the dictionary.

We can add key-value pairs in the dictionary using the following syntax

Dictionary_name[key] =value

>>>food_details["Salt"] = "Salty"
>>>food_details["Type"] = "Chicken Pizza"
>>>print(food_items)
   {'name': 'Pizza', 'price': 500, 'quantity': 5, 'Salt': 'salty', 'Type': 'Chicken pizza'}

Modifying key-value pairs in the dictionary.

We can simply modify the existing key-value pairs in the dictionary by overwriting the key-value pair with a new value as below

Dictionary_name['existing_key'] = new_value Example

>>>food_details = {"name" : "Pizza"}
>>>print(food_details)
   {'name' : 'Pizza']
>>>food_details["name"] = "Burger"
>>>print("Now food is: ", food_details)
   Now food is: {'name' : 'Burger'}
Removing the Key-Value pairs from the dictionary.
  • Using del keyword

    Using the del keyword we can delete the specific key-value or as well as the whole dictionary. After the deletion of the whole dictionary, if we try to print it, an error will be raised.

    Example
    
    food_details = {
         "name": "Pizza",
         "price": 500,
         "quantity": 5
    } #initial dictionary.
    
    del food_details['name']
    print("After specific key deletion: ", food_details)
    
    del food_details
    print(food_details)
    Output
                
    After specific key deletion: {'prince' : 500, 'quantity' : 5}
    NameError: name 'food_details' is not defined
  • Using popitem() method

    This method returns and removes the last (key, value) pair from the dictionary

    Example
    
    food_details = {
                "name": "Pizza",
                "price": 500,
                "quantity": 5
    } #initial dictionary.
    
    popped_element = food_details.popitem()
    print("Dictionary now: ", food_details)
    print("Popped_element: ", popped_element)
    Output
    
    Dictionary now: {'name': 'Pizza', 'price': 500}
    Popped_element: ('quantity', 5)
     
  • Using clear() method

    With this method, we can delete all the items from the dictionary at once.

    Example
    
    food_details = {
                "name": "Pizza",
                "price": 500,
                "quantity": 5
    } #initial dictionary.
    
    food_details.clear()
    print("After deleting entire dictionary items: ", food_details)
             
    Output
    
        After deleting entire dictionary items: {}
     
Looping through a Dictionary.

A dictionary is a data structure that can store millions of key-value pairs. To access these key-value pairs in the dictionary, python provides a feature for looping through the dictionary. From the dictionary, sometimes we need to access both keys and values, sometimes we need to access either only keys or only values, depending on the cases we can loop a dictionary in various ways.

  • Looping through all key-value pairs

    We can access both keys and values from a dictionary using for loop in the following way

    
    for key,value in Dictionary-name.items():
         #block of code
            
    Example

    Let us consider a dictionary as follows and loop through it

    
    user_info = {
                'First-Name' : 'James',
                'Last-Name' : 'Taylor',
                'User-Name' : 'James321',
                'Email' : '[email protected]',
                'Mobile' : '+12243359185'
    }
    
    for key, value in user_info.items():
        print("Key: ",key)
        print("Value: ",value)
            
    Output
    
    Key: First-Name
    Value: James
    
    Key: Last-Name
    Value: Taylor
    
    Key: User-Name
    Value: James321
    
    Key: Email
    Value: [email protected]
    
    Key: Mobile
    Value: +12243359185
     
  • Looping through all the keys.

    We can access all the keys from a dictionary using for loop in the following way.

    
    for key in Dictionary-name.keys():
        #block of code
    Example
    
    user_info = {
                'First-Name' : 'James',
                'Last-Name' : 'Taylor',
                'User-Name' : 'James321',
                'Email' : '[email protected]',
                'Mobile' : '+12243359185'
    }
    
    for key in user_info.keys():
        print("Key: ",key)
    Output
    
    Key: First-Name
    Key: Last-Name
    Key: User-Name
    Key: Email
    Key: Mobile
     
  • Looping through all the values.

    We can access all the values from a dictionary using for loop in the following way

    
    for key in Dictionary-name.values():
        #block of code
            
            
    Example
    
    user_info = {
                'First-Name' : 'James',
                'Last-Name' : 'Taylor',
                'User-Name' : 'James321',
                'Email' : '[email protected]',
                'Mobile' : '+12243359185'
    }
    
    for value in user_info.values():
        print("Value: ",value)
            
    Output
    
    Value: James
    Value: Taylor
    Value: James321
    Value: [email protected]
    Value: +12243359185
             

Nested Dictionary

A nested dictionary is a dictionary that contains another dictionary inside it. We can store a dictionary as a value inside another dictionary as follows.

    
dictionary = {
    'First_dict' : {'Key1':'value1','key2':'value2','keyN':'ValueN'},
    'Second_dict' : {'Key1':'value1','key2':'value2','keyN':'ValueN'},
    'Third_dict' : {'Key1':'value1','key2':'value2','keyN':'ValueN'}
}
    
Creating a Nested Dictionary

We can create a nested dictionary by putting dictionaries as the value to various keys of a dictionary. We use the ':' operator to make key-value pair.

Example
    
dictionary = {
    'info1' : {'Name':'Jack','Age':32},
    'info2' : {'Name':'Goerge','Age':25},
    'info3' : {'Name':'Harry','Age':28}
}
print(dictionary)
    
Output

{'info1': {'Name': 'Jack', 'Age': 32}, 'info2': {'Name': 'Goerge', 'Age': 25}, 'info3': {'Name': 'Harry','Age': 28}}
 
Accessing Nested Dictionary

To access any dictionary we can use the indexing operator []

Example

dictionary = {
    'info1' : {'Name':'Jack','Age':32},
    'info2' : {'Name':'Goerge','Age':25},
    'info3' : {'Name':'Harry','Age':28}
}
print(dictionary)

print(dictionary['info1']['Name'],dictionary['info1']['Age'])
print(dictionary['info2']['Name'],dictionary['info2']['Age'])
print(dictionary['info3']['Name'],dictionary['info3']['Age'])
Output

Jack 32
Goerge 25
Harry 28
 
Adding Items to Nested Dictionary

We can add items to the nested dictionary in the following two ways

  • Dictionary[Dict][key] = 'value'
  • Dictionary[Dict] = {'key' : 'value'}
Example

#taking empty dictionary
dict = {}
dict['dict1'] = {}
dict['dict2'] = {}

print(dict)

#adding some items to empty sub-dictionaries
dict['dict1'][1] = 'A'
dict['dict1'][2] = 'B'

dict['dict2'][1] = 'C'
dict['dict2'][2] = 'D'

print(dict)

#We can enter whole dictionary in this way too
dict['dict3'] = {1 : 'E', 2 : 'F'}
print(dict)

Output
    
{'dict1': {}, 'dict2': {}}
{'dict1': {1: 'A', 2: 'B'}, 'dict2': {1: 'C', 2: 'D'}}
{'dict1': {1: 'A', 2: 'B'}, 'dict2': {1: 'C', 2: 'D'}, 'dict3': {1: 'E', 2: 'F'}}
    
Deleting a Nested Dictionary

We can delete a nested dictionary using the del statement or pop() method as follows

Example

dictionary = {'dict1': {1: 'A', 2: 'B'}, 'dict2': {1: 'C', 2: 'D'}, 'dict3': {1: 'E', 2: 'F'}}

print(dictionary)

del dictionary['dict1']
print(dictionary)

dictionary.pop('dict2')
dictionary.pop('dict3')
print(dictionary)
Output

{'dict1': {1: 'A', 2: 'B'}, 'dict2': {1: 'C', 2: 'D'}, 'dict3': {1: 'E', 2: 'F'}}
{'dict2': {1: 'C', 2: 'D'}, 'dict3': {1: 'E', 2: 'F'}}
{}
 
The Dictionary Comprehensions

Dictionary comprehension is an elegant and quick procedure for making a dictionary.

Example1

We can create a dictionary in the following way which is straight forward process using for loop.


#let us make a dictionary containing natural number as key and its corresponding cube as value
cube = dict()

for i in range(1,6):
    cube[i] = i**3

print(cube)


A similar thing can also be done using dictionary comprehension which is shorter and quicker than the above method.


d ={i: i**3 for i in range(1,6)}
    
Output

{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
 
Example2

Let us make a dictionary of the teenage student from the given dictionary.


#Given dictionary
dictionary = {
    'Jack':12,
    'Goerge':25,
    'Harry':17,
    'Marry':25,
    'Luna':15
}

#Dictionary of the student with age below 20
teenage_student = {name: age for name,age in dictionary.items() if age<20}
print(teenage_student)
Output

{'Jack': 12, 'Harry': 17, 'Luna': 15}