Python

Check if all Elements in a List are None

Check if all Elements in a List are None in Python

A collection is an ordered list of values. There could be various types of values. A list is a mutable container. This means that existing ones can be added to, deleted from, or changed.

The Python list represents the mathematical concept of a finite sequence. List values are referred to as list items or list elements. The same value may appear multiple times in a list. Each event is regarded as a distinct element.

Given a list, the task is to check if all elements in a list are none or not.

Examples:

Input:

givenlist = [None, None, None, None, None, None]

Output:

The givenlist's elements are all None

Check if all items in a list are none in python

There are several ways to check if all items in a list are none some of them are:

Method #1:Using for loop

Iterate through all of the items in a list using a for loop, checking if each item is None or not. Break the loop as soon as a non None object is identified, as this indicates that all items in the list are not None. If the loop ends without finding even a single non-None object, it proves that the list’s items are all None.

Let’s make a function that takes a list and checks whether any of the things are none or not using the logic described above.

Below is the implementation:

# function which checks if all the elements are none in the list are none
def checkNone(givenlist):
    # initializing result to true
    res = True
    # traversing the givenlist
    for element in givenlist:
        if element is not None:
          # all the elements are not null hence return false
            return False
    # if all the elements are null then return the result i.e true
    return res


# driver code
# given list
givenlist = [None, None, None, None, None, None]
# passing givenlist to checkNone function
answer = checkNone(givenlist)
if(answer):
    print("The givenlist's elements are all None")
else:
    print("givenlist elements are not null")

Output:

The givenlist's elements are all None

Method #2:Writing custom function

Create a generic function that checks whether all items in a list are the same and also matches the specified element.

As an argument, this function takes a list and an object. Then, using the same logic as the previous example, determines if all items in the given list match the given object. This feature can be used to see if any of the things in a list are None.

Below is the implementation:

# function which checks if all the elements are none in the list are none
def checkNone(givenlist, value):
    # initializing result to true
    res = True
    # traversing the givenlist
    for element in givenlist:
        if element != value:
          # all the elements are not null hence return false
            return False
    # if all the elements are null then return the result i.e true
    return res


# driver code
# given list
givenlist = [None, None, None, None, None, None]
# passing givenlist to checkNone function
answer = checkNone(givenlist, None)
if(answer):
    print("The givenlist's elements are all None")
else:
    print("givenlist elements are not null")

Output:

The givenlist's elements are all None

Method #3:Using List Comprehension

We generated a Boolean list from the current list using list comprehension. Each element in this bool list corresponds to an item in the main list. Basically, in List Comprehension, we iterated through the given list, checking if each member was None or not. If it’s None, put True in the bool list; otherwise, put False. All() was used to see whether the bool list contained only True or not. If the all() function returns True, our main list only contains None.

Below is the implementation:

# function which checks if all the elements are none in the list are none
def checkNone(givenlist, value):
    # all() +list comprehension  function
    return all([element == value for element in givenlist])


# driver code
# given list
givenlist = [None, None, None, None, None, None]
# passing givenlist to checkNone function
answer = checkNone(givenlist, None)
if(answer):
    print("The givenlist's elements are all None")
else:
    print("givenlist elements are not null")

Output:

The givenlist's elements are all None

Method #4:Using count() function

Using the count() function, we can count the number of none values in the list.

Return True if the count of none values equals the length of the list, otherwise False.

Below is the implementation:

# function which checks if all the elements are none in the list are none
def checkNone(givenlist):
    # using count function
    # counting none values in list
    countnone = givenlist.count(None)
    # return true if count is equal to length
    return countnone == len(givenlist)


# driver code
# given list
givenlist = [None, None, None, None, None, None]
# passing givenlist to checkNone function
answer = checkNone(givenlist)
if(answer):
    print("The givenlist's elements are all None")
else:
    print("givenlist elements are not null")

Output:

The givenlist's elements are all None

Related Programs:

Check if all Elements in a List are None in Python Read More »

Pretty print nested dictionaries – dict of dicts

Python: Pretty Print Nested Dictionaries – Dict of Dicts

Dictionaries are Python’s implementation of an associative list, which may be a arrangement . A dictionary may be a collection of key-value pairs that are stored together. A key and its value are represented by each key-value pair.

To an infinite depth, a dictionary may include another dictionary, which can contain dictionaries, and so on. This is referred to as a nested dictionary.

Nested dictionaries are one among several ways during which structured information is represented (similar to records or structures in other languages).

In this article, we’ll look at how to print a nested dictionary in a visually beautiful and readable format.

Examples:

Input:

nesteddict = {
'hello': {'www': 100, 'yyy': 'Helloworld'},
'this': {'www': 'vikram', 'age': 20, 'DOB': 'FEB'},
'BTechGeeks': {'PLACE': 'HYDERABAD', 'PINCODE': 500000,
'PYTHON': {'FUNCTIONS': 'Built in', 'year': 1999}},
}

Output:

{
    "hello": {
        "www": 100,
        "yyy": "Helloworld"
    },
    "this": {
        "www": "vikram",
        "age": 20,
        "DOB": "FEB"
    },
    "BTechGeeks": {
        "PLACE": "HYDERABAD",
        "PINCODE": 500000,
        "PYTHON": {
            "FUNCTIONS": "Built in",
            "year": 1999
        }
    }
}

Print nested dictionaries in pretty way

There are several ways to print nested dictionaries in pretty way some of them are:

1)Using generic function

We can only call the values() function of a dictionary for a normal dictionary to get an iterable sequence of values. However, a value can be another dictionary object in a nested dictionary. To do this, we need to call the values() function again and get a new iterative sequence of values and search for dictation objects in those values. This is possible with recurrence in a simple way.

To print all of the key-values in this dictionary, we wrote a function that will recursively go through the nested dictionary and print all of the key-values.

Below is the implementation:

def printNested(nesteddict):
    # Traverse the dictionary
    for key, value in nesteddict.items():
        # If the value is of the dictionary type, then print
        # all of the key and values within the nested dictionary.
        if isinstance(value, dict):
            print(key, "  : {\n")
            printNested(value)
            print("\n}\n")

        else:
            print("\t", key, " : ", value)


# given nested_dictionary
nesteddict = {
    'hello':    {'www': 100, 'yyy': 'Helloworld'},
    'this':    {'www': 'vikram', 'age': 20, 'DOB': 'FEB'},
    'BTechGeeks':    {'PLACE': 'HYDERABAD', 'PINCODE': 500000,
                      'PYTHON': {'FUNCTIONS': 'Built in', 'year': 1999}},
}
# passing nested dictionary to printNested Function
printNested(nesteddict)

Output:

hello   : {

	 www  :  100
	 yyy  :  Helloworld

}

this   : {

	 www  :  vikram
	 age  :  20
	 DOB  :  FEB

}

BTechGeeks   : {

	 PLACE  :  HYDERABAD
	 PINCODE  :  500000
PYTHON   : {

	 FUNCTIONS  :  Built in
	 year  :  1999

}
}

2)Using json module

Rather than writing our own functions, we can use the json module to print a dictionary of dictionaries in a format that looks like json.

Below is the implementation:

import json as json
# given nested_dictionary
nesteddict = {
    'hello':    {'www': 100, 'yyy': 'Helloworld'},
    'this':    {'www': 'vikram', 'age': 20, 'DOB': 'FEB'},
    'BTechGeeks':    {'PLACE': 'HYDERABAD', 'PINCODE': 500000,
                      'PYTHON': {'FUNCTIONS': 'Built in', 'year': 1999}},
}
# using json to print the nested dict
print(json.dumps(nesteddict, indent=4))

Output:

{
    "hello": {
        "www": 100,
        "yyy": "Helloworld"
    },
    "this": {
        "www": "vikram",
        "age": 20,
        "DOB": "FEB"
    },
    "BTechGeeks": {
        "PLACE": "HYDERABAD",
        "PINCODE": 500000,
        "PYTHON": {
            "FUNCTIONS": "Built in",
            "year": 1999
        }
    }
}

3)Using pandas to print as table

We can print the nested dictionary a table using the pandas module.

Below is the implementation:

import pandas as pd
# given nested_dictionary
nesteddict = {
    'hello':    {'www': 100, 'yyy': 'Helloworld'},
    'this':    {'www': 'vikram', 'age': 20, 'DOB': 'FEB'},
    'BTechGeeks':    {'PLACE': 'HYDERABAD', 'PINCODE': 500000,
                      'PYTHON': {'FUNCTIONS': 'Built in', 'year': 1999}},
}
print(pd.DataFrame(nesteddict).T)

Output:

                         DOB            PINCODE      PLACE        ...     age      www       yyy
hello                 NaN            NaN              NaN           ...     NaN    100         Helloworld
this                   FEB              NaN              NaN           ...     20        vikram    NaN
BTechGeeks      NaN            500000         HYDERABAD ... NaN      NaN        NaN

[3 rows x 7 columns]

 

 
Related Programs:

Python: Pretty Print Nested Dictionaries – Dict of Dicts Read More »

Python: Remove characters from string by regex and 4 other ways

Removing characters from string by regex and many other ways in Python.

In this article we will get to know about deleting characters from string in python by regex() and various other functions.

Removing characters from string by regex :

sub() function of regex module in Python helps to get a new string by replacing a particular pattern in the string by a string replacement. If no pattern found, then same string will be returned.

Removing all occurrences of a character from string using regex :

Let we want to delete all occurrence of ‘a’ from a string. We can implement this by passing in sub() where it will replace all ‘s’ with empty string.

#Program :

import re
origin_string = "India is my country"

pattern = r'a'

# If found, all 'a' will be replaced by empty string
modif_string = re.sub(pattern, '', origin_string )
print(modif_string)
Output :
Indi is my country

Removing multiple characters from string using regex in python :

Let we want to delete all occurrence of ‘a’, ‘i’. So we have to replace these characters by empty string.

#Program :

import re
origin_string = "India is my country"
pattern = r'[ai]'
# If found, all 'a' & 'i' will be replaced by empty string
modif_string = re.sub(pattern, '', origin_string )
print(modif_string) 
Output :
Ind s my country

Removing characters in list from the string in python :

Let we want to delete all occurrence of ‘a’ & ‘i’ from a string and also these characters are in a list.

#Program :

import re
origin_string = "India is my country"
char_list = ['i','a']
pattern = '[' + ''.join(char_list) + ']'
# All charcaters are removed if matched by pattern
modif_string = re.sub(pattern, '', origin_string)
print(modif_string)
Output :
Ind s my country

Removing characters from string using translate() :

str class of python provide a function translate(table). The characters in the string will be replaced on the basis of mapping provided in translation table.

Removing all occurrence of a character from the string using translate() :

Let we want to delete all occurrence of ‘i’ in a string. For this we have to pass a translation table to translate() function where ‘i’ will be mapped to None.

#Program :

origin_string = "India is my country"
# If found, remove all occurence of 'i' from string
modif_string = origin_string.translate({ord('i'): None})
print(modif_string)
Output :
Inda s my country

Removing multiple characters from the string using translate() :

Let, we want to delete ‘i’, ‘y’ from the above string.

#Program :

org_string= "India is my country"
list_char = ['y', 'i']
# Remove all 's', 'a' & 'i' from the string
mod_string = org_string.translate( {ord(elem): None for elem in list_char} )
print(mod_string)
Output :
Inda s m countr

Removing characters from string using replace()  :

Python provides str class, from which the replace() returns the copy of a string by replacing all occurrence of substring by a replacement. In the above string we will try to replace all ‘i’ with ‘a’.

#Program :

origin_string = "India is my country"
# Replacing all of 's' with 'a'
modif_string = origin_string.replace('i', 'a')
print(modif_string)
Output :
Indaa as my country

Removing characters from string using join() and generator expression :

Let we have a list with some characters. For removing all characters from string that are in the list, we would iterate over each characters in the string and join them except those which are not in the list.

#Program :

origin_string= "India is my country"
list_char = ['i', 'a', 's']
# Removes all occurence of 'i', 'a','s' from the string
modif_string = ''.join((elem for elem in origin_string if elem not in list_char))
print(modif_string)
Output :
Ind  my country

Removing characters from string using join and filter() :

filter() function filter the characters from string based on logic provided in call back function. If we provide a call back function as lambda function, it checks if the characters in the list are filtered are not. After that it joins the remaining characters to from a new string i.e. it eliminates all occurrence of characters that are in the list form a string.

#Programn :

origin_string = "India is my country"
list_char = ['i', 'a', 's']
# To remove all characters in list, from the string
modif_string = ''.join(filter(lambda k: k not in list_char, origin_string))
print(modif_string)
Output :
Ind  my country

 

Python: Remove characters from string by regex and 4 other ways Read More »

Pandas: Sort rows or columns in Dataframe based on values using Dataframe.sort_values()

How to sort rows or columns in Dataframe based on values using Dataframe.sort_values() in Python ?

In this article we will get to know about how to sort rows in ascending & descending order based on values in columns and also sorting columns based on value in rows using member function DataFrame.sort_values().

DataFrame.sort_values() :

Pandas library contains a Dataframe class which provide a function to arrange the contents of dataframe.

Syntax : DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last')

where,

  • by:  Column names or index labels where sorting is to be done.
  • axis:  If axis=0. names by argument will be taken as column names and If axis=1, names by argument will be taken as row index labels
  • ascending:  If True: Ascending Sorting , Else: Descending Sorting
  • inplace: When true in-place operation performed in dataframe
  • na_position: If True: It will sort the current dataframe , Else: Return a sorted copy of dataframe instead of modifying the dataframe.

Sorting Dataframe rows based on a single column :

To sort rows in dataframe based on ‘Team’ column, we will pass ‘Team’ as argument.

#Program :

import pandas as sc

# List of Tuples as Players
players = [ ('Curran', 325, 'CSK') ,
             ('Ishan', 481, 'MI' ) ,
             ('Vijay', 106, 'SRH') ,
             ('Pant', 224, 'Delhi' ) ,
             ('Seifert', 65, 'KKR' ) ,
             ('Hooda', 440, 'PK' )
              ]

# To Create DataFrame object
datafObjs = sc.DataFrame(players, columns=['Name', 'Runs', 'Team'], index=['i', 'ii', 'iii', 'iv', 'v', 'vi'])

# Sorting the rows of dataframe by column 'Team'
datafObjs = datafObjs.sort_values(by ='Team' )

print("Now the sorted Dataframe based on column 'Team' is : ")
print(datafObjs)
Output :
 Now the sorted Dataframe based on column 'Team' is :
        Name  Runs   Team
i     Curran   325    CSK
iv      Pant   224  Delhi
v    Seifert    65    KKR
ii     Ishan   481     MI
vi     Hooda   440     PK
iii    Vijay   106    SRH

Sorting Dataframe rows based on multiple column :

To sort all rows of dataframe based on Team & Runs column.

#Program :

import pandas as sc

# List of Tuples as Players
players = [ ('Curran', 325, 'CSK') ,
             ('Ishan', 481, 'MI' ) ,
             ('Vijay', 106, 'SRH') ,
             ('Pant', 224, 'Delhi' ) ,
             ('Seifert', 65, 'KKR' ) ,
             ('Hooda', 440, 'PK' )
              ]

# To Create DataFrame object
datafObjs = sc.DataFrame(players, columns=['Name', 'Runs', 'Team'], index=['i', 'ii', 'iii', 'iv', 'v', 'vi'])

# Sorting the rows of dataframe by column 'Team'
datafObjs = datafObjs.sort_values(by =['Runs', 'Team'])

print("Now the sorted Dataframe on the basis of columns 'Name' & 'Marks' : ")
print(datafObjs)
Output :
Now the sorted Dataframe on the basis of columns 'Name' & 'Marks' :
        Name   Runs   Team
v     Seifert    65       KKR
iii    Vijay      106     SRH
iv     Pant      224    Delhi
i      Curran   325     CSK
vi     Hooda   440     PK
ii     Ishan      481     MI

Sorting Dataframe rows based on columns in Descending Order :

Here we will sort the dataframe in descending order by passing value as false in argument ascending.

#Program :

import pandas as sc

# List of Tuples as Players
players = [ ('Curran', 325, 'CSK') ,
             ('Ishan', 481, 'MI' ) ,
             ('Vijay', 106, 'SRH') ,
             ('Pant', 224, 'Delhi' ) ,
             ('Seifert', 65, 'KKR' ) ,
             ('Hooda', 440, 'PK' )
              ]

# To Create DataFrame object
datafObjs = sc.DataFrame(players, columns=['Name', 'Runs', 'Team'], index=['i', 'ii', 'iii', 'iv', 'v', 'vi'])

# Sortimg rows of dataframe by column 'Name' in descending manner
datafObjs = datafObjs.sort_values(by ='Name' , ascending=False)

print("Now the sorted Dataframe on basis of column 'Name' in Descending manner : ")
print(datafObjs)
Output :
Now the sorted Dataframe on basis of column 'Name' in Descending manner :
        Name   Runs   Team
iii     Vijay      106    SRH
v     Seifert     65      KKR
iv    Pant       224     Delhi
ii     Ishan      481     MI
vi     Hooda   440     PK
i      Curran     325    CSK

Sorting Dataframe rows based on a column in Place :

Here we will sort the dataframe based on single column in place with argument inplace and value True.

#Program :

import pandas as sc

# List of Tuples as Players
players = [ ('Curran', 325, 'CSK') ,
             ('Ishan', 481, 'MI' ) ,
             ('Vijay', 106, 'SRH') ,
             ('Pant', 224, 'Delhi' ) ,
             ('Seifert', 65, 'KKR' ) ,
             ('Hooda', 440, 'PK' )
              ]

# To Create DataFrame object
datafObjs = sc.DataFrame(players, columns=['Name', 'Runs', 'Team'], index=['i', 'ii', 'iii', 'iv', 'v', 'vi'])

# Sorting e rows of the dataframe by column 'Name' inplace
datafObjs.sort_values(by='Team' , inplace=True)

print("Now the sorted Dataframe based on a single column 'Team' inplace : ")
print(datafObjs)
Output :
Now the sorted Dataframe based on a single column 'Team' inplace :
        Name  Runs   Team
i      Curran   325    CSK
iv     Pant     224     Delhi
v      Seifert    65    KKR
ii      Ishan    481     MI
vi     Hooda   440     PK
iii     Vijay     106     SRH

Sorting columns of a Dataframe based on a single or multiple rows :

Let’s take a example where column of a dataframe is to be sorted on the  basis of single or multiple rows.

#program :

import pandas as sc

# List of Tuples as matrix
matrix = [(11, 2, 33),
          (4, 55, 6),
          (77, 8, 99),
          ]

# To create a DataFrame object like a Matrix
datafObjs = sc.DataFrame(matrix, index=list('abc'))

print("Sorting the daataframe based on single rows or multiple rows: ")
print(datafObjs)
Output :
Sorting the daataframe based on single rows or multiple rows:
    0   1   2
a  11   2  33
b   4  55   6
c  77   8  99

Sorting columns of a Dataframe based on a single row :

Now from above dataframe let’s sort the dataframe on basis of ‘b’ row.

#program :

import pandas as sc

# List of Tuples as matrix
matrix = [(11, 2, 33),
          (4, 55, 6),
          (77, 8, 99),
          ]

# To create a DataFrame object like a Matrix
datafObjs = sc.DataFrame(matrix, index=list('abc'))
datafObjs = datafObjs.sort_values(by ='b', axis=1)

print("Now the sorted Dataframe on the basis of single row index label 'b' : ")
print(datafObjs)
Output :
Now the sorted dataframe is sorted on the basis of row index label 'b' :
    0   2   1
a  11  33   2
b   4   6  55
c  77  99   8

Sorting columns of a Dataframe in Descending Order based on a single row :

Here we will sort columns of the dataframe in descending order based on single row.

Here we will sort columns of a Dataframe on basis of multiple rows by passing value in ascending as false.

#Program :

import pandas as sc

# List of Tuples as matrix
matrix = [(11, 2, 33),
          (4, 55, 6),
          (77, 8, 99),
          ]

# To create a DataFrame object like a Matrix
datafObjs = sc.DataFrame(matrix, index=list('abc'))

# Sorting the columns of a dataframe in descending order based on a single row with index label 'b'
datafObjs = datafObjs.sort_values(by='b', axis=1, ascending=False)

print("Now the sorted Dataframe on the basis of single row index label 'b' in descending order :")
print(datafObjs)
Output :
Now the sorted Dataframe on the basis of single row index label 'b' in descending order :

    1   2   0
a   2  33  11
b  55   6   4
c   8  99  77

Sorting columns of a Dataframe based on a multiple rows :

 Here the columns of dataframe are sorted on the  basis of multiple rows with passing labels ‘b’ & ‘c’ and axis=1.

#program :

import pandas as sc

# List of Tuples as matrix
matrix = [(11, 2, 33),
          (4, 55, 6),
          (77, 8, 99),
          ]

# To create a DataFrame object like a Matrix
datafObjs = sc.DataFrame(matrix, index=list('abc'))

# Sorting columns of the dataframe based on a multiple row with index labels 'b' & 'c'
datafObjs = datafObjs.sort_values(by =['b' , 'c' ], axis=1)

print("Now the sorted Dataframe based on multiple rows index label 'b' & 'c' :")
print(datafObjs)
Output :
Now the sorted Dataframe based on multiple rows index label 'b' & 'c' :

    0   2   1
a  11  33   2
b   4   6  55
c  77  99   8

Want to expert in the python programming language? Exploring Python Data Analysis using Pandas tutorial changes your knowledge from basic to advance level in python concepts.

Read more Articles on Python Data Analysis Using Padas – Modify a Dataframe

Pandas: Sort rows or columns in Dataframe based on values using Dataframe.sort_values() Read More »

Python Numpy : Select elements or indices by conditions from Numpy Array

How to elect elements or indices by conditions from Numpy Array in Python ?

In this article we will see how we can select and print elements from a given Numpy array provided with multiple conditions.

Selecting elements from a Numpy array based on Single or Multiple Conditions :

When we apply a comparison operator to a numpy array it is applied to each & every elements of the array. It is seen that True or False will be returned as bool array accordingly when its elements satisfies the condition.

#Program :

import numpy as sc

# To create a numpy array from 2 to 25 with interval 23
num_arr = sc.arange(2, 25, 3)

# To compare with all elements in array
bool_arr = num_arr < 15
print(bool_arr)

Output :
[ True  True  True  True  True False False False]

If we pass the resulted bool Numpy array in [] operartor then it will form a new Numpy Array with elements which were found True in corresponding bool Numpy array.

#Program :

import numpy as sc

num_arr = sc.arange(2, 25, 3)
bool_arr = num_arr < 15
print(bool_arr)

# Those elements will be selected where it is True at corresponding value in bool array
new_arr = num_arr[bool_arr]
print(new_arr)
Output :
[ True  True  True  True  True False False False]
[ 2  5  8 11 14]

Select elements from Numpy Array which are divisible by 5 :

We can select and print those elements which are divisible by 5 from given Numpy array.

 

#Program :

import numpy as sc

# Numpy arrray with elements frrm 3 to 25
num_arr = sc.arange(3, 25, 1)

# To select those numbers which are divisible by 5
new_arr = num_arr[num_arr%5==0]

print(new_arr)
Output :
[ 5  10  15  20 ]

Select elements from Numpy Array which are greater than 10 and less than 18 :

We can select and print those elements which are smaller than 10 and greater than 18 from given Numpy array.

 

#Program :

import numpy as sc

# Numpy arrray with elements frrm 3 to 25
num_arr = sc.arange(3, 25, 1)

# To select those numbers which are greater than 10 and smaller than 18
new_arr = num_arr[(num_arr > 10) & (num_arr < 18)]

print(new_arr)
Output :
[11 12 13 14 15 16 17]

 

Python Numpy : Select elements or indices by conditions from Numpy Array Read More »

Python : Create boolean Numpy array with all True or all False or random boolean values

How to create boolean Numpy array with all True or all False or random boolean values in Python ?

This article is about creating boolean Numpy array with all True or all False or random boolean values. Here we will discuss various ways of creating boolean Numpy array. So let’s start the topic.

Approach-1 : Creating 1-D boolean Numpy array with random boolean values

Python’s Numpy module provide random.choice( ) function which will create a boolean Numpy array with some random values.

Syntax : numpy.random.choice(a, size=None, replace=True, p=None)

where,

  • a: A Numpy array from which random values will be generated
  • size: Shape of array that is to b generated
  • replace: Here the sample is with or without replacement

To create a 1-D Numpy array with random true and false values, we will initially take a bool array and pass the array to numpy.random.choice() with some size which will generate a array with random true and false values.

So, let’s see how it actually works.

#Program :

import numpy as sc

# bool Array for random sampling with only 2 values i.e. True anf False
sample_Barr = [True, False]

# To create a numpy array with random true and false with size 5
bool_Narr = sc.random.choice(sample_Barr, size=5)

print('Numpy Array with random values: ')
print(bool_Narr)
Output :
Numpy Array with random values:
[False False False  True False]

Approach-2 : Creating 2-D boolean Numpy array with random values :

For implementing this we can pass the size of 2D array as tuple in random.choice( ) function.

So, let’s see how it actually works.

#Program :

import numpy as sc

# bool Array for random sampling with only 2 values i.e. True anf False
sample_Barr = [True, False]

# To create a 2D numpy array with random true and false values
bool_Narr = sc.random.choice(sample_Barr, size=(3,3))

print('2D Numpy Array with random values: ')
print(bool_Narr)
Output :
2D Numpy Array with random values:
[[False False False]
[False  True  True]
[ True False  True]]

Approach-3 : Create a 1-D Bool array with all True values :

We can use numpy.ones( ) function to form boolean Numpy array with all True values. nump.ones( ) creates a numpy array with initializing value with 1, later dtype argument is passed as bool which converts all 1 to True.

So, let’s see how it actually works.

#Program :

import numpy as sc

# To create a 1D numpy array with all true values
bool_Narr = sc.ones(5, dtype=bool)

print('1D Numpy Array with all true values: ')
print(bool_Narr)

Output :
1D Numpy Array with all true values:
[ True  True  True  True  True]

Approach-4 : Create a 1-D Bool array with all False values :

We can use numpy.zeros( ) function to form boolean Numpy array with all True values. nump.zeros( ) creates a numpy array with initializing value with 0, later dtype argument is passed as bool which converts all 0 to False.

So, let’s see how it actually works.

# Program :

import numpy as sc

# To create a 1D numpy array with all false values
bool_Narr = sc.zeros(5, dtype=bool)

print('1D Numpy Array with all false values: ')
print(bool_Narr)
Output :
1D Numpy Array with all false values:
[False False False False False]

Approach-5 :  Creating 2-D Numpy array with all True values :

Here also numpy.ones( ) including passing the dtype argument as bool can be used to generate all values as true in a 2D  numpy array.

So, let’s see how it actually works.

# Program :

import numpy as sc

# To create a 2D numpy array with all true values
bool_Narr = sc.ones((3,4), dtype=bool)

print('2D Numpy Array with all true values: ')
print(bool_Narr)
Output :
2D Numpy Array with all true values:
[[ True  True  True  True]
[ True  True  True  True]
[ True  True  True  True]]

Approach-6 :  Creating 2D Numpy array with all False values :

Here also numpy.zeros( ) including passing the dtype argument as bool can be used to generate all values as false in a 2D  numpy array.

So, let’s see how it actually works.

#Program :

import numpy as sc

# To create a 2D numpy array with all true values
bool_Narr = sc.zeros((3,4), dtype=bool)

print('2D Numpy Array with all true values: ')
print(bool_Narr)
Output :
2D Numpy Array with all false values:
[[False False False False]
[False False False False]
[False False False False]]

Converting a List to bool Numpy array :

Approach-7 : Convert a list of integers to boolean numpy array :

Here we will pass dtype arguement as bool in numpy.array( ) function where each and every elements in the list will be converted as true/ false values, i.e. all 0s will be converted to false and any integer other than 0 to true.

So, let’s see how it actually works.

#Program :

import numpy as sc

# Integers list
list_ele = [8,55,0,24,100,0,0,-1]

# To convert a list of integers to boolean array
bool_Narr = sc.array(list_ele, dtype=bool)

print('Boolean Numpy Array: ')
print(bool_Narr)
Output :
Numpy Array:
[ True  True  False  True  True  False False  True]

Approach-8 : Convert a heterogeneous list to boolean numpy array :

In python, list can contain elements with different data types i.e. heterogeneous in nature. But Numpy arrays are homogeneous in nature i.e. elements with same data type, so it will convert all 0s to false and any other values which can be of any data type to true.

So, let’s see how it actually works.

#Program :

import numpy as sc

# Integers list
list_ele = [8,55,0,24.56,100,0,-85.6,"Satya"]

# To convert a list of integers to boolean array
bool_Narr = sc.array(list_ele, dtype=bool)

print('Boolean Numpy Array: ')
print(bool_Narr)
Output :
Boolean Numpy Array:
[ True  True  False  True  True False  True  True]

 

Python : Create boolean Numpy array with all True or all False or random boolean values Read More »

Python Pandas : Drop columns in DataFrame by label Names or by Index Positions

How to drop columns in DataFrame by label Names or by Index Positions in Python ?

In this article, we are going to demonstrate how to drop columns in a dataframe by their labels or index. So, let’s start exploring the topic in detail.

In dataframe there is a function drop() which can be used to drop columns.

Syntax – DataFrame.drop

(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')

Where,

  • labels : The label or the labels we want to delete are passed here.
  • index : The index of the position to be deleted
  • columns : If it is True it deletes the columns, else the rows
  • axis : If axis is 1 it considers the columns like the columns. If 0, it works on rows.
  • inplace : If it is False then it doesn’t modify the dataframe, it returns a new one. If it is set to True it modifies the dataframe.

We will be using the following dataset as example :

     Regd     Name        Age      City           Exp
a    10         Jill             16.0     Tokyo         10
b    11         Rachel      38.0     Texas           5
c    12         Kirti          39.0      New York    7
d    13        Veena       40.0     Texas           21
e    14        Lucifer      NaN     Texas           30
f     15        Pablo        30.0     New York     7
g    16       Lionel        45.0     Colombia    11

Delete a Single column in DataFrame by Column Name :

We can delete a single column just by passing its name into the function. Let’s try deleting ‘Age’ column from the Dataframe.

Let’s see the program how to implement this.

#Program :

import numpy as np
import pandas as pd

# Example data
students = [(10,'Jill',    16,     'Tokyo',    10),
            (11,'Rachel',  38,     'Texas',     5),
            (12,'Kirti',   39,     'New York',  7),
            (13,'Veena',   40,     'Texas',    21),
            (14,'Lucifer', np.NaN, 'Texas',    30),
            (15,'Pablo',   30,     'New York',  7),
            (16,'Lionel',  45,     'Colombia', 11) ]
#Creating a dataframe object
dfObj = pd.DataFrame(students, columns=['Regd','Name','Age','City','Exp'], index=['a', 'b', 'c' , 'd' , 'e' , 'f', 'g']) 
#Modifying the dataframe and storing it into a new object
modDfObj = dfObj.drop('Age' , axis='columns')
print(modDfObj)
Output :
    Regd     Name      City         Exp
a    10        Jill           Tokyo       10
b    11      Rachel     Texas          5
c    12       Kirti       New York    7
d    13      Veena     Texas          21
e    14      Lucifer     Texas         30
f    15       Pablo     New York    7
g    16      Lionel    Colombia    11

Drop Multiple Columns by Label Names in DataFrame :

To delete multiple columns by name we just have to pass all the names as a list into the function. Let’s try deleting ‘Age’ and ‘Exp’

Let’s see the program how to implement this.

#Program :

import numpy as np
import pandas as pd

# Example data
students = [(10,'Jill',    16,     'Tokyo',    10),
            (11,'Rachel',  38,     'Texas',     5),
            (12,'Kirti',   39,     'New York',  7),
            (13,'Veena',   40,     'Texas',    21),
            (14,'Lucifer', np.NaN, 'Texas',    30),
            (15,'Pablo',   30,     'New York',  7),
            (16,'Lionel',  45,     'Colombia', 11) ]
#Creating a dataframe object
dfObj = pd.DataFrame(students, columns=['Regd','Name','Age','City','Exp'], index=['a', 'b', 'c' , 'd' , 'e' , 'f', 'g']) 
#Modifying the dataframe without the columns and storing it into a new object
modDfObj = dfObj.drop(['Age' , 'Exp'] , axis='columns')
print(modDfObj)
Output :
   Regd   Name     City
a    10     Jill          Tokyo
b    11   Rachel     Texas
c    12    Kirti        New York
d    13    Veena     Texas
e    14   Lucifer     Texas
f    15    Pablo      New York
g    16   Lionel     Colombia

Drop Columns by Index Position in DataFrame :

In case we know the index position of the columns we want to drop, we can pass them into the function. Let’s try deleting the same two columns as above but with their index position.

Let’s see the program how to implement this.

#Program :

import numpy as np
import pandas as pd

# Example data
students = [(10,'Jill',    16,     'Tokyo',    10),
            (11,'Rachel',  38,     'Texas',     5),
            (12,'Kirti',   39,     'New York',  7),
            (13,'Veena',   40,     'Texas',    21),
            (14,'Lucifer', np.NaN, 'Texas',    30),
            (15,'Pablo',   30,     'New York',  7),
            (16,'Lionel',  45,     'Colombia', 11) ]
#Creating a dataframe object
dfObj = pd.DataFrame(students, columns=['Regd','Name','Age','City','Exp'], index=['a', 'b', 'c' , 'd' , 'e' , 'f', 'g']) 
#Modifying the dataframe without the columns and storing it into a new object by passsing the index of the columns
modDfObj = dfObj.drop([dfObj.columns[2] , dfObj.columns[4]] ,  axis='columns')
print(modDfObj)
Output :
    Regd   Name      City
a    10     Jill           Tokyo
b    11    Rachel     Texas
c    12     Kirti         New York
d    13    Veena      Texas
e    14    Lucifer     Texas
f    15     Pablo       New York
g    16    Lionel      Colombia

Drop Columns in Place :

In case we don’t want a new dataframe object to hold the modified values, but want to store it in the same object, we can do it by passing inplace= True. Let’s use the previous example for this.

Let’s see the program how to implement this.

#Program :

import numpy as np
import pandas as pd

# Example data
students = [(10,'Jill',    16,     'Tokyo',    10),
            (11,'Rachel',  38,     'Texas',     5),
            (12,'Kirti',   39,     'New York',  7),
            (13,'Veena',   40,     'Texas',    21),
            (14,'Lucifer', np.NaN, 'Texas',    30),
            (15,'Pablo',   30,     'New York',  7),
            (16,'Lionel',  45,     'Colombia', 11) ]
#Creating a dataframe object
dfObj = pd.DataFrame(students, columns=['Regd','Name','Age','City','Exp'], index=['a', 'b', 'c' , 'd' , 'e' , 'f', 'g']) 
#Modifying the dataframe without the columns and storing it into the same object 
dfObj.drop([dfObj.columns[2] , dfObj.columns[4]] ,  axis='columns',inplace = True)
print(dfObj)
Output :
     Regd     Name      City
a    10          Jill         Tokyo
b    11       Rachel     Texas
c    12        Kirti       New York
d    13       Veena     Texas
e    14      Lucifer     Texas
f    15       Pablo    New York
g    16     Lionel     Colombia

Drop Column If Exists :

In case the column/row does not exist we can do a check beforehand to avoid further bugs in the program. We can do so by using the same function drop( ) , it checks for the columns and if it is not found it returns KeyError which we can handle by an if-else condition.

#program :

import numpy as np
import pandas as pd

# Example data
students = [(10,'Jill',    16,     'Tokyo',    10),
            (11,'Rachel',  38,     'Texas',     5),
            (12,'Kirti',   39,     'New York',  7),
            (13,'Veena',   40,     'Texas',    21),
            (14,'Lucifer', np.NaN, 'Texas',    30),
            (15,'Pablo',   30,     'New York',  7),
            (16,'Lionel',  45,     'Colombia', 11) ]
#Creating a dataframe object
dfObj = pd.DataFrame(students, columns=['Regd','Name','Age','City','Exp'], index=['a', 'b', 'c' , 'd' , 'e' , 'f', 'g']) 
#Checking for a non-existent column
if 'Last Name' in dfObj.columns :
    dfObj.drop('Last Name' ,  axis='columns')
    print(dfObj)
else :
    print("The column was not found")
Output :
The column was not found

Want to expert in the python programming language? Exploring Python Data Analysis using Pandas tutorial changes your knowledge from basic to advance level in python concepts.

Read more Articles on Python Data Analysis Using Padas – Remove Contents from a Dataframe

Python Pandas : Drop columns in DataFrame by label Names or by Index Positions Read More »

Python: numpy.ravel() function Tutorial with examples

Understanding numpy.ravel() function with its examples in Python

In this article we will discuss about numpy.ravel( ) function and using it in different methods to flatten a multidimensional numpy array.

numpy.ravel( ) is a built-in function provided by Python’s numpy module.

Syntax - numpy.ravel(a, order='C')

where,

  1. a : array_like- It is a numpy array or list where elements will be read in given order
  2. order – The order in which numpy array will be read
  • C‘= Read elements in row by row manner i.e. using C-like index order
  • F‘= Read elements in row by row manner i.e. using Fortan-like index order
  • K‘= Read elements from array based on memory order of items.

Flatten a matrix or 2D array to 1D array using numpy.ravel( ) :

While converting a 2-D array to 1-D array, in numpy.ravel( ) default value of order parameter ‘C’ is passed, so elements in 2-D array is read row by row.

# program :

import numpy as sc

# To create a 2D Numpy array
twoD_array = sc.array([ [11, 2, 33],
                        [44, 5, 66],
                        [77, 8, 99]])

print('2D Numpy Array:')
print(twoD_array)

# To get a flattened view 1D of 2D Numpy array

flatn_array = sc.ravel(twoD_array)
print('Flattened 1D view:')
print(flatn_array)
Output :
2D Numpy Array:
[[11 2 33]
[44 5 66]
[77 8 99]]
Flattened 1D view:
[11 2 33 44 5 66 77 8 99]

numpy.ravel() returns a view :

It is seen that when we modify the view of the object, the changes is observed not only in flattened 1D object but also in the original 2D Numpy array.

#program :

import numpy as sc

# To create a 2D Numpy array

twoD_array = sc.array([ [11, 2, 33],
[44, 5, 66],
[77, 8, 99]])

flatn_array = sc.ravel(twoD_array)

#Modifying 5th element of the array
flatn_array[4]= 100

print('Modified 2D array:')
print(twoD_array)
print('Modified Flattened 1D view:')
print(flatn_array)
Output :
Modified 2D array:
[[ 11  2  33]
[ 44 100  66]
[ 77  8  99]]
Modified Flattened 1D view:
[ 11  2  33  44 100  66  77  8  99]

Accessing original array from the flattened view object  :

Flattened view object has an attribute base, which points to original Numpy array.     

#Program :

import numpy as sc

# To create a 2D Numpy array
twoD_array = sc.array([ [11, 2, 33],
[44, 5, 66],
[77, 8, 99]])

flatn_array = sc.ravel(twoD_array)

#Modifying 5th element of the array
flatn_array[4]= 100

print('Modified Flattened 1D view:')
print(flatn_array)
print('2D Numpy array')
# Here ndarray.base point to retrieve the original Numpy array
print(flatn_array.base)
Output :
Modified Flattened 1D view:
[ 11  2  33  44 100  66  77  8  99]
2D Numpy array
[[ 11  2  33]
[ 44 100  66]
[ 77  8  99]]

Using numpy.ravel() along different axis with order parameter :

ndarray.ravel() accepts parameter order i.e. ‘C’ or ‘F’ or ‘A’. The default value is ‘C’.

Get Flatten view of 2D array Row wise :

If there is mo parameter passed in ravel() function, then default value i.e. ‘C’ is taken. So, now the 2-D array will be read row wise.

# Program :

import numpy as sc

# To create a 2D Numpy array
twoD_array = sc.array([ [11, 2, 33],
[44, 5, 66],
[77, 8, 99]])


# getting flattened view of 2D array read row by row
flatn_array = sc.ravel(twoD_array, order='')

print('Flattened View row by row:')
print(flatn_array)
Output :
Flattened View row by row:
[11 2 33 44 5 66 77 8 99]

Get Flatten view of 2D array Column wise :

When we will pass ‘F in ravel() function, then the elements will be read column by column.

#program :

import numpy as sc

# creating a 2D Numpy array
twoD_array = sc.array([ [11, 2, 33],
[44, 5, 66],
[77, 8, 99]])

# getting flattened view of 2D array read column by column
flatn_array = sc.ravel(twoD_array, order='F')
print('Flattened View column by column:')
print(flatn_array)
Output :
Flattened View column by column:
[11 44 77 2 5 8 33 66 99]

Get Flatten view of 2D array based on memory layout :

We can also get the transpose view of 2-D Numpy array

# Program :

import numpy as sc

# To create a 2D Numpy array
twoD_array = sc.array([ [11, 2, 33],
[44, 5, 66],
[77, 8, 99]])


# To get transpose view of 2D array
transp_arr = twoD_array.T
print('Transpose View of the 2D Numpy Array')
print(transp_arr)
Output :
Transpose View of the 2D Numpy Array
[[11 44 77]
[2   5   8]
[33 66 99]]

We can also get a flattened 1-D view from transpose 2-D Numpy array

#Prtogram :

import numpy as sc

# To create a 2D Numpy array
twoD_array = sc.array([ [11, 2, 33],
[44, 5, 66],
[77, 8, 99]])


# To get transpose view of 2D array
transp_arr = twoD_array.T

# To get a flattened view of transpose 2D array
flatn_array = sc.ravel(transp_arr, order='C')

print('Flattened View of transpose 2D Numpy array:')
print(flatn_array)
Output :
Flattened View of transpose 2D Numpy array:
[11 44 77 2 5 8 33 66 99]

In the previous scenario, the original memory layout was ignored while current layout of view object was used. In this case we would try to get flattened view of the transposed Numpy array based on memory layout by using argument as ‘A’. So, in place of current layout in view, memory layout of the original array will be used.

# Program :

import numpy as sc

# creating a 2D Numpy array
twoD_array = sc.array([ [11, 2, 33],
[44, 5, 66],
[77, 8, 99]])

# getting transpose view of 2D array
transp_arr = twoD_array.T

# getting a flattened view of transpose 2D array in row-wise manner
flatn_array = sc.ravel(twoD_array, order='A')

print('Flattened View of transposed Numpy array based on memory layout :')
print(flatn_array)
Output :
Flattened View of transposed Numpy array based on memory layout :
[11 2 33 44 5 66 77 8 99]

Flatten a list of lists using numpy.ravel() :

We can also use list of lists to get flattened view instead of taking array.

# Program :

import numpy as sc

list_lists = [[1, 2, 3, 4],

[4, 5, 6, 7],

[7, 8, 9, 10],

[10, 11, 12, 13]]

# Creating a flattened numpy array from list of lists

flatn_array = sc.ravel(list_lists)

print('Flattened 1D Numpy Array:')

print(flatn_array)
Output :
Flattened 1D Numpy Array:
[ 1  2  3  4  4  5  6  7  7  8  9 10 10 11 12 13]

We can even convert flattened 1-D numpy array to a list.

# Program :

import numpy as sc

list_lists = [[1, 2, 3, 4],
[4, 5, 6, 7],
[7, 8, 9, 10],
[10, 11, 12, 13]]


flatn_array = sc.ravel(list_lists)
print('Flattened List from array:')

# Converting array to list
print(list(flatn_array))
Output :
Flattened List from array:
[1, 2, 3, 4, 4, 5, 6, 7, 7, 8, 9, 10, 10, 11, 12, 13]

 

Python: numpy.ravel() function Tutorial with examples Read More »

Drop first row of pandas dataframe (3 Ways)

How to delete first row of pandas dataframe in Python ?

In this article we will discuss about different ways to delete first row of pandas dataframe in Python.

Method-1 : By using iloc attribute :

An iloc attribute is there in Pandas by using which we can select a portion of the dataframe that may be few columns or rows which is simply called as position based indexing.

Syntax - df.iloc[start_row:end_row , start_column, end_column]

Where,

  • start_row : It refers to the row position from where it will start selection.(Default value is 0)
  • end_row : It refers to the row position from where it will end selection.(Default value is upto last row of the dataframe)
  • start_column : It refers to the column position from where it will start selection.(Default value is 0)
  • end_column : It refers to the column position from where it will end selection.(Default value is upto last column of the dataframe)

So, we can select all the rows of the dataframe except the first row and assign back the selected rows to the original variable which will give an effect that the first row has been deleted from the dataframe.

To achieve this, select dataframe from row-2 and select all columns. Row-2 means we will select from index position-1 (as index position starts from 0 in dataframe) upto last row. And to select all columns use default values i.e (:)

i.e

df = df.iloc[1: , :]

So let’s see the implementation of it.

# Program :

import pandas as pd
# List of tuples created
empoyees = [('A',1,'a',10),
            ('B',2,'b',20),
            ('C',3,'c',30) ,
            ('D',4,'d',40)]
# DataFrame object created
df = pd.DataFrame(  empoyees, columns=['Upper', 'Smaller', 'Lower', 'Bigger'])
print("Contents of the original Dataframe : ")
print(df)
# Dropping first row 
df = df.iloc[1: , :]
print("Contents of modified Dataframe : ")
print(df)
Output :
Contents of the original Dataframe : 
  Upper  Smaller  Lower Bigger
0   A         1          a           10
1   B         2          b           20
2   C         3          c           30
3   D        4           d          40
Contents of modified Dataframe : 
    Upper Smaller Lower Bigger
1     B       2            b        20
2     C       3            c        30
3     D       4            d        40

Method-2 : Using drop() function :

There is an drop() function in Panda’s dataframe which can be used to delete any rows from the dataframe.  To make sure that rows only will be deleted then select axis=0 and pass argument inplace=True.

So let’s see the implementation of it.

# Program :

import pandas as pd
# List of tuples created
empoyees = [('A',1,'a',10),
            ('B',2,'b',20),
            ('C',3,'c',30) ,
            ('D',4,'d',40)]
# DataFrame object created
df = pd.DataFrame(  empoyees, columns=['Upper', 'Smaller', 'Lower', 'Bigger'])
print("Contents of the original Dataframe : ")
print(df)
# Dropping first row 
df.drop(index=df.index[0], 
        axis=0, 
        inplace=True)
        
print("Contents of modified Dataframe : ")
print(df)
Output : 
Contents of the original Dataframe : 
    Upper Smaller Lower Bigger
0     A           1         a       10
1     B           2         b       20
2     C           3         c       30
3     D           4         d      40
Contents of modified Dataframe : 
    Upper Smaller Lower Bigger
1     B         2           b       20
2     C         3           c       30
3     D        4            d       40

Method-3 : Using tail() function :

In python, dataframe provides a tail(n) function which returns last ‘n’ rows. So to select all the rows except first row we can pass tail(n-1) which means first row deleted. And it assign back the selected rows to the original variable.

So let’s see the implementation of it.

# Program :

import pandas as pd
# List of tuples created
empoyees = [('A',1,'a',10),
            ('B',2,'b',20),
            ('C',3,'c',30) ,
            ('D',4,'d',40)]
# DataFrame object created
df = pd.DataFrame(  empoyees, columns=['Upper', 'Smaller', 'Lower', 'Bigger'])
print("Contents of the original Dataframe : ")
print(df)

# Deleting first row by selecting last n-1 rows
df = df.tail(df.shape[0] -1)
        
print("Contents of modified Dataframe : ")
print(df)
Output :
Contents of the original Dataframe : 
     Upper Smaller Lower Bigger
0      A         1          a         10
1      B         2          b         20
2      C         3          c         30
3      D         4          d        40
Contents of modified Dataframe : 
    Upper Smaller Lower Bigger
1     B         2          b       20
2     C         3          c       30
3     D         4          d       40

 

Drop first row of pandas dataframe (3 Ways) Read More »

Python: Dictionary get() function tutorial and examples

Dictionary get() function tutorial with examples in Python.

In this article, we are going to see how we can use the dict.get( ) function with some examples.

Syntax : dict.get(key, defaultValue)

 Where,

  1. Key : The key that is to be searched inside the dictionary.
  2. defaultValue : The default value to be returned in case we don’t find the key inside the dictionary.

The function returns the value associated with the key in case the key is found in the dictionary. Otherwise it returns the default value that we provides to it, if there was no default value provided it returns none.

Get value by key in a dictionary using dict.get() :

Let us take an example where there are 4 elements inside a dictionary. We will try to find the value associated with “B”.

#Program :

dictWords = {
    "A": 65,
    "B": 32,
    "V": 34,
    "U": 87 }
#Fucntion returns the value associated with the key ‘'B'’
dictValue = dictWords.get('B')
#Value associateed with the key 'B'
print('Value of the key "B" : ', dictValue)
Output : 
Value of the key "B" : 32

Get the value of a key that does not exist in a dictionary :

 In the previous example we were looking for the value associated with an existing key, here we will try to see what happens when the key doesn’t exist in the dictionary.

#Program :

dictWords = {
    "A": 56,
    "B": 23,
    "V": 43,
    "U": 78
}
#Fucntion returns the value associated with the non- existent key 'D'
dictValue = dictWords.get('D')
#Value associateed with the key 'D'
print('Value of the non-existent key "D" : ', dictValue)
Output :
Value of the non-existent key "D" : None

When the key “D” which was absent was passed into the function, the compiler prints none, which is the default value (None is the default value as we have not specified any other value in the place of default value).

Get the default value for the key that does not exist in a dictionary :

 Here we will again check for the same non-existent key, however this time we will provide the function with a default value.

#Program :

dictWords = {
    "A": 56,
    "B": 23,
    "V": 43,
    "U": 78
}
#Fucntion returns the value associated with the non- existent key 'D' i.e. default value
dictValue = dictWords.get('D',"NA")
#Value associateed with the key 'D'
print('Value of the non-existent key "D" : ', dictValue)
Output :
Value of the non-existent key "D" : NA

It returns the default value that we provided when the key we were searching for was non-existent.

Dict.get(key) vs dict[key]

 We can also use the [ ] to find out the value associated to a key inside a dictionary.

So, let’s see the implementation of it.

#Program :

dictWords = {
    "A": 56,
    "B": 23,
    "V": 43,
    "U": 78
}
#Fucntion returns the value associated with the key 'B' using []
dictValue = dictWords['B']
#Value associateed with the key 'B'
print('Value of the key "B" : ', dictValue)
Output :
Value of the key "B" : 23

It does the same thing when we check for an existent key. Let’s try with the non-existent one.

Output :
KeyError: 'D'

So the only difference in these two methods is that while looking for a non-existent key using the .get( ) function we get none as output or a default value that we assigned. However while using [ ] we get a KeyError in the program.

Python: Dictionary get() function tutorial and examples Read More »