Satyabrata Jena

Python : How to Sort a list of strings ? | list.sort()

How to sort a list of strings using list.sort() in python ?

In this article we will discuss about 4 different ways of sorting a list of strings.

In python, list is a versatile data type which stores multiple elements in a single variable without caring about the types of data.

Syntax : my_list = [element1, element2, element3]

The 4 ways are

  1. By Alphabetical Order
  2. By Reverse Alphabetical Order
  3. By String Length
  4. By Numeric Order

List provides a sort() method by using which we can sort the elements of list from lower order to higher order.

So, let’s start exploring the topic.

Method-1 : By Alphabetical Order

Let’s see a program how it sorts in alphabetical order.

#Program :

#List Of Strings
my_list = ['bat' , 'ant', 'cat', 'eye', 'dog']
my_list.sort()
print(my_list)
Output :
['ant' , 'bat', 'cat', 'dog', 'eye']

Method-2 : By Reverse Alphabetical Order

Let’s see a program how it sorts in alphabetical order.

#Program :

#List Of Strings
my_list = ['bat' , 'ant', 'cat', 'eye', 'dog']
my_list.sort(reverse=True)
print(my_list)
Output :
['eye' , 'do', 'cat', 'bat', 'ant']

Here, sort() method accepts another argument reverse, and it it is True then it sorts the element. Default value is False. When set True, it sorts element in reverse order.

Method-3 : By String Length

Let’s see a program how it sorts in alphabetical order.

#Program :

#List Of Strings
my_list = ['apple' , 'ant', 'aeroplane', 'auto', 'a']
my_list.sort(key=len)
print(my_list)
Output :
['a' , 'ant',  'auto', 'apple', 'aeroplane']

Here, sort() method accepts another argument i.e key. During sorting each element of list will be compared with each other.

Syntax : list.sort(key=function)

Here we have passed len() function as key function. And all the element are sorted as per string length.

Method-4 : By Numeric Order

Suppose we have a list of strings, where each element are of numbers. There we can use int() as key function.

Let’s see a program how it sorts in alphabetical order.

#Program : 

#List Of Strings 
my_list = ['4' , '6', '1', '3', '2'] 
my_list.sort(key=int) 
print(my_list)
Output :
['1','2','3','4','6']
How to create DataFrame from Dictionary

Python Pandas : How to create DataFrame from dictionary ?

How to create DataFrame from dictionary in Python ?

In this article we will discuss about various ways of creating DataFrame object from dictionaries.

So, let’s start exploring different approaches to achieve this result.

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.

Method-1 : Create DataFrame from Dictionary using default Constructor :

In python DataFrame constructor accepts n-D array, dictionaries etc.

Syntax : pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)
#program :

# import pandas library
import pandas as pd
  
# dictionary with list object in values
data = {
    'Name' : ['Satya', 'Omm', 'Rakesh'],
    'Age' : [21, 21, 23],
    'From' : ['BBSR', 'RKL', 'KDP']
}
  
# creating a Dataframe object 
df_obj = pd.DataFrame(data)
  
df_obj


Output :

         Name    Age   From
0      Satya      21      BBSR
1      Omm      21      RKL
2      Rakesh    23       KDP

All keys in dictionary are converted to column name and values in dictionaries converted column data.

Method-2 : Create DataFrame from Dictionary with custom indexes :

#program :

# import pandas library
import pandas as pd
  
# dictionary with list object in values
data = {
    'Name' : ['Satya', 'Omm', 'Rakesh'],
    'Age' : [21, 21, 23],
    'From' : ['BBSR', 'RKL', 'KDP']
}
  
# creating a Dataframe object 
df_obj = pd.DataFrame(data, index = ['a','b','c'])
  
df_obj

Output :
        Name    Age     From
a      Satya      21      BBSR
b     Omm       21     RKL
c     Rakesh     23     KDP

By passing index list, we can avoid the default index.

Method-3 : Create DataFrame from Dictionary and skip data

By skipping some of the items of dictionary, we can also create a DataFrame object from dictionary

Let’s see the implementation of that.

#program :

# import pandas library
import pandas as pd
  
# dictionary with list object in values
data = {
    'Name' : ['Satya', 'Omm', 'Rakesh'],
    'Age' : [21, 21, 23],
    'From' : ['BBSR', 'RKL', 'KDP']
}
  
# creating a Dataframe object 
#items skipped with key 'Age'
df_obj = pd.DataFrame(data, columns=['name', 'From'])
  
df_obj


Output :
       Name        From
0      Satya        BBSR
1     Omm          RKL
2     Rakesh       KDP

Method-4 : Create DataFrame from Dictionary with different Orientation

DataFrame can also be created from dictionary using DataFrame.from_dict() function.

DataFrame.from_dict(data, orient='columns', dtype=None)

It accepts orientation too, where we can pass the orientation as index then the keys which were used as columns during creating DataFrame now they will be used as index.

Let’s see the implementation of that.

#program :

# import pandas library
import pandas as pd
  
# dictionary with list object in values
data = {
    'Name' : ['Satya', 'Omm', 'Rakesh'],
    'Age' : [21, 21, 23],
    'From' : ['BBSR', 'RKL', 'KDP']
}
  
# creating a Dataframe object 
#items skipped with key 'Age'
df_obj = pd.DataFrame(data,orient='index')
  
df_obj


Output :

             0           1            2

Aame   Satya   Omm     Rakesh

From     BBSR    RKL       KDP

Age       21         21         23

Method-5 : Create DataFrame from nested Dictionary :

Suppose we have a nested dictionary, then we ill directly pass it in DataFrame constructor where the keys of dictionary will be used as column.

Let’s see the implementation of that.

#program :

# import pandas library
import pandas as pd
  
# dictionary with list object in values
# Nested Dictionary
data = { 
0 : {
    'Name' : 'Satya',
    'Age' : 21,
    'From' : 'BBSR'
    },
1 : {
    'Name' : 'Omm',
    'Age' : 21,
    'From' : 'RKL'
    },
2 : {
    'Name' : 'Rakesh',
    'Age' : 23,
    'From' : 'KDP'
    }
}
  
# creating a Dataframe object 
#items skipped with key 'Age'
df_obj = pd.DataFrame(data)
  
df_obj

Output :
             0           1            2
Aame   Satya   Omm     Rakesh
From     BBSR    RKL       KDP
Age       21         21         23

Read more Articles on Python Data Analysis Using Padas – Creating Dataframe Objects:

Python: How to add or append values to a set ?

How to add or append values to a set in Python ?

In python add() method or append() method is used to simply add an item in set, tuple, dictionary etc.. but this method doesn’t add an element  if the entered element already present before it.

Adding a single element to the set :

Set is a data type which stores multiple items in a single variable and the items can be of different types.

Syntax : set.add(element)

It accepts an element as an argument and if that element is not present then it add it o the set.

Add a value to the set using add() function :

#program :

#Set initialized
my_set = {1, 2, "Hello", 3, "Hi"} 
# Adding a single element in set 
my_set.add(5) 
print(my_set)
Output :
{1,2,3,5'Hello','Hi'}

Adding a duplicate element to the set :

As set contains only unique elements, so duplicate elements so it will not not add the element again means set has no effect.

Let’s see an example program for it.

#program :

#Set initialized
my_set = {1, 2, "Hello", 3, "Hi"} 
# Adding 'Hello' in set 
my_set.add("Hello") 
print(my_set)
Output :
{1,2,3,5'Hello','Hi'}

Adding immutable objects to the set using add() function :

Set contains immutable elements. So, int, strings, bytes, frozen sets, tuples can be added as these are immutable object. But we can not add a list as it is mutable object.

Let’s see an example program for it how we can add a tuple to the set using add function.

#Program :

#Set initialized
my_set = {1, 2, "Hello", 3, "Hi"}
# Adding a tuple in set
my_set.add((4, 5))
print(my_set)
Output :
{1, 2, (4,5),"Hello", 3, "Hi"}

Adding a mutable object to set will give TypeError :

Suppose we are trying to add a list as it is mutable object. It will give Type error.

Let’s see an example program for it.

#Program :

#Set initialized
my_set = {1, 2, "Hello", 3, "Hi"}
# Adding a tuple in set
my_set.add([21, 31])
print(my_set)
Output :
TypeError: unhashable type: 'list'

Adding multiple elements to the set :

By using update() method we can add elements to the set.

Syntax : set.update(*args)
#Program :

#Set initialized
my_set = {1, 2, "Hello", 3, "Hi"}
# Adding 10,20,30 in set
#update() method is used
my_set.update((10, 20, 30))
print(my_set)
Output :
{1,2,3,5'Hello','Hi',10,20,30}

Adding elements from multiple sequences to the set :

Suppose we want to add a list, tuple at a time. Then let’s see how it works.

#Program :

#Set initialized
my_set = {1, 2, "Hello", 3, "Hi"}

#list initialized
my_list= [10, 20, 3]
#tuple initialized
my_tuple = (31, 32)
#update() method is used
my_set.update(my_list,my_tuple)
print(my_set)
Output :
{1,2,3,5'Hello','Hi',10,20,30,31,32}

Adding dictionary keys to the set :

#Program :

#Set initialized
my_set = set()
#dictionary initialized
my_dict = {'Satya': 11, 'Omm': 12, 'Nitya': 15}
#only keys ill be added
my_set.update(my_dict)
print(my_set)
Output :
{'Satya','Omm','Nitya'}

When we will pass the dictionary inside the update() method then only key will be added in the set.

Adding dictionary values to the set :

#Program :

#Set initialized
my_set = set()
#dictionary initialized
my_dict = {'Satya': 10, 'Omm': 20, 'Nitya': 30}
#only keys ill be added
my_set.update(my_dict.values())
print(my_set)
Output :
{10,20,30}

When we will pass the dictionary_name.values() inside the update() method then only values will be added in the set.

 

Python : Get number of elements in a list, list of lists or nested list

How to get the number of elements in a list, list of lists or nested list in Python ?

In this article we will discuss about different ways to get number of elements in a list, lists of lists or nested list Lists. As we know in python, lists are used to store multiple values in an ordered sequence inside a single variable.  Each element inside the list is called an item.

Syntax : my_list = [ element1, element2, element3, .....]

where,

  • elements/items are placed inside square brackets [].
  • items are separated by , symbol.
  • It can contain any number of items.
  • elements can be of different types i.e string, float, integer etc.

Count elements in a flat list :

To count elements in a flat list we have to use the len( ) function. This len( ) function is a built-in function that returns the number of items inside a list, tuple, or string.

Syntax : len(name_of_list)

Let’s see an implementation of it.

#Program :

#list of items
listElem = ['contempt', 'speech', 'notorious', 'north','south','aware','ex']
#finding the length of list
length = len(listElem)
print('Number of elements inside the list : ', length)
Output : 
Number of elements in list :  7

Count elements in list of lists :

To count the number of elements inside a list of lists we can not use the len( ) function because as the function works it will return the number of lists inside the list.

Let’s see an implementation of it.

#Program :

#list of items
listElem = [[10,20,30],[40,50,60],[70,80,90]]
#finding the length of list of lists
length = len(listElem)
print('Number of elements inside the list : ', length)
Output : 
Number of elements in list :  3

As you can see there are 9 elements inside the list, however, the function returned 3, which is the number of lists inside the list.

So to count elements we can use two methods.

Method-1 : Using for loop to iterate over the list and count the elements :

#Program : 

#list of lists 
listElem2D = [[10,20,30],[40,50,60],[70,80,90]] 
count = 0 
#counting number of elements 
for listElem in listElem2D: 
 count += len(listElem) 
print('Total Number of elements : ', count)
Output :
Total Number of elements :  9

Method-2 : Using list comprehension :

Using list comprehension to iterate over the list, build a new list of sizes and calculate the number of elements by passing it to the built-in sum( ) function.

#Program :

#list of lists
listElem2D = [[10,20,30],[40,50,60],[70,80,90]]
#finding number of elements
count = sum( [ len(listElem) for listElem in listElem2D])                 
print('Total Number of elements : ', count)
Output : 
Total Number of elements :  9

Use list.__len__() to count elements in a list :

We can call the __len__() member function of list to get the size the list.

#Program : 

#list of items 
listElem = [10,20,30,40,50] 
#finding the length of list of lists 
length = listElem.__len__()
print('Number of elements inside the list : ', length)
Output :
Number of elements inside the list : 5

Count elements in a nested list :

Nested lists might contain several lists, lists of lists, or values together so we can not use any of the above approaches for it. So to calculate the values we have to write a function that takes the nested list and returns the number of items inside it.

Let’s see an implementation of it.

#Program :

def getSizeOfNestedList(listOfElem):
    count = 0
    for elem in listOfElem:
        if type(elem) == list:
            count += getSizeOfNestedList(elem)
        else:
            count += 1    
    return count

#list of lists
listElemNested = [[10,20,30],[40,50,60],[70,80,90],100,120,140,[[110,130],150],170]
count = getSizeOfNestedList(listElemNested)                
print('Total Number of elements : ', count)
Output :
Total Number of elements :  16

 

Python : 6 Different ways to create Dictionaries

How we can create dictionaries by multiple ways in python ?

Dictionary in python is one of the important datatype which is used to store data values in key : value pair.

Syntax of dictionary :

dictionary_name = {key1: value1, key2: value2}

where,

  • key1, key2… represents keys in a dictionary. These keys can be of any data type like string, integer, tuple, etc. But keys needs to be unique.
  • value1, value2… represents values in dictionary. These values can be numbers, strings, list or list within a list etc.
  • key and value is separated by : symbol.
  • key-value pair symbol is separated by , symbol.

Approach-1: Creating Empty Dictionary :

By 2 ways we can create empty dictionary.

Method-1 : By using { } empty brackets :

Let’s see the implementation of it with a program.

#Program :

# Empty dictionary created using empty brackets
covid_case_dict = {}
print(covid_case_dict)
Output :
{ }

Method-2: By using using dict() :

Let’s see the implementation of it with a program.

#Program :

# Empty dictionary created using dict()
covid_case_dict = dict()
print(covid_case_dict)
Output :
{ }

Approach-2: Creating Dictionaries with literals :

By passing key : value pairs literals we can create dictionary.

Let’s see the implementation of it with a program.

#Program :

# dictionary created using key-value literals
covid_case_dict = {"January":100000, "February":200000, "March":300000}
print(covid_case_dict)
Output :
{"January":100000, "February":200000, "March":300000}

Approach-3: Creating Dictionaries by passing parameters in dict constructor :

By creating dictionary constructor and passing  key-value pairs within it also we can create a dictionary.

Let’s see the implementation of it with a program.

#Program :

#dictionary created using dictionary constructor
covid_case_dict = dict(January=100000, February=200000, March=300000)
print(covid_case_dict)
Output :
{"January":100000, "February":200000, "March":300000}

Approach-4: Creating Dictionaries by a list of tuples :

We can create a dictionary by passing  list of tuple within dict constructor.

Let’s see the implementation of it with a program.

#Program :

# list of tuples
list_of_Tuples = [("January",100000), ("February",200000), ("March",300000)]
#dictionary created by passing tuple in dict constructor
covid_case_dict = dict(list_of_Tuples)
print(covid_case_dict)
Output :
{"January":100000, "February":200000, "March":300000}

Approach-5: Creating a Dictionary by a list of keys and initializing all with the same value :

We can create a dictionaries by assigning same vales to all the keys.

Suppose we a dictionary of keys. Let’s see how we can initialize all keys with same value.

#Program :

# list of keys 
covid_case_list = ["Januray", "February", "March"]
# create and Initialize a dictionary 
#use list elements as keys and with same value 100000
covid_case_dict = dict.fromkeys(covid_case_list,100000 )
print(covid_case_dict)
Output :
{"January":100000, "February":100000, "March":100000}

Approach-6: Creating a Dictionary by two lists :

If we have two lists, then also we can create a dictionary. For that we can use the elements of the first list as keys and we can use the elements of the second list as values.

In python there is a zip( ) function which we will be used and it will iterate over two lists parallelly.

Let’s see the implementation of it with a program.

#Program :

# First list, its elements will be used as keys 
covid_case_list1 = ["Januray", "February", "March"]

# Second list, its elements will be used as values
covid_case_list2 = [100000, 200000, 300000]
#two lists are merged using zip() to create dictionary
covid_case_dict = dict( zip(covid_case_list1,covid_case_list2))
print(covid_case_dict)
Output : 
{"January":100000, "February":100000, "March":100000}

Remove a key from Dictionary in Python | del vs dict.pop() vs comprehension

How to remove a key from dictionary using del vs dict.pop() vs comprehension in python ?

As we know, Dictionary plays an important role in python data structure.

  • The elements are written with in { }curly brackets, having keys and values.
  • Each key-value pair mapped with the key to its related value.
  • In Dictionaries duplicates are not allowed.
Syntax : mydict = {key1: value1, key2: value2}

In this article, we will discuss about different ways to remove a key from dictionary in python.

Let us assume we have a dictionary with correspondent keys and values:

#dictionary with keys with their correspondent values
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}

Now we will see different method to delete an key from dictionary :

Method -1 : Using dict.pop( ) method :

This pop() method is used to delete a key and its value in its place. The advantage over using del is that it provides a mechanism to print the desired value if you try to remove a non-existent spelling. Secondly it also returns the value of the key that is removed as well as performs a simple delete operation.

#Program :

#dictionary test_dict
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}
#this key will be deleted
key_to_be_deleted = 'Sagar'
# As 'Sagar' key is present in dictionary, so pop() will delete
# its entry and return its value
result = test_dict.pop(key_to_be_deleted, None)
print("Deleted item's value = ", result)
print("Updated Dictionary :", test_dict)
Output
Deleted item's value = 36
Updated Dictionary : {'Ram': 32, 'Dhruv': 45}

In case the key does not exist :

We use try/except method to avoid error. We know key ‘Soni’ is not in dictionary. So, an error will generate. To avoid error try/except method will be used.

#Program :

#dictionary test_dict
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}

#Deleting key which does not exist i.e Soni
key_to_be_deleted = 'Soni'
try:
    test_dict.pop(key_to_be_deleted)
except KeyError:
    print('That Key is not in the dictionary')
Output :
That is not present in the dictionary

Method-2 : Using items() & for loop :

By using item() method and for loop we will iterate over the dictionary. When the key that will be deleted will be matched then delete that key.

Let’s see a program how it’s implemented.

#Program :

# Dictionary with keys and values
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}
# key that to be deleted
key_to_be_deleted = 'Dhruv'
new_dict = {}
#using for loop 
#Iterate one by one key#If found that key then delete
for key, value in test_dict.items():
 if key is not key_to_be_deleted:
  new_dict[key] = value
test_dict = new_dict
print(test_dict)
Output
{'Ram': 32, 'Dhruv': 45}

Here for deletion we used for loop and We created a new temporary dictionary and then duplicated it for all key-value pairs in the original dictionary. During iteration, we copy the key and value pair into a new temporary dictionary only if the key is not equal to the key to be deleted. Once the duplication finished, we copied the contents of the new temporary dictionary into the original dictionary.

Method-3: Using items() & Dictionary Comprehension :

Utilizing the logic of the above example we use items() & dictionary comprehension.

#Program :

# Dictionary with keys and values
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}
# key that to be deleted
key_to_be_deleted = 'Ram'
test_dict = {key: value for key, value\
                  in test_dict.items()\
                  if key is not key_to_be_deleted}
print(test_dict)
Output:
{'Ram': 32, 'Dhruv': 45}

Method-4: Using del keyword :

We can use the del statement to delete a key-value pair from the dictionary regarding on the key.

Syntax : del dict[key]

Let’s use it-

#Program :

# Dictionary of keys &values
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}
# Deleting an item from dictionary using del
del test_dict['Dhruv']
print(test_dict)
Output:
{'Sagar': 36, 'Ram':32}

In case the key does not exist :
Suppose we want to delete key 'Soni', which does not exist then we can use try-except to avoid any exception.

Let’s see the implementation of it.

#Program :

# Dictionary of keys &values
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}
# If key exist in dictionary then delete it using del.
key_to_be_deleted = 'Soni'
try:
 del test_dict[key_to_be_deleted]
except KeyError:
 print('That key is not present in the dictionary')
Output:
That key is not present in the dictionary

7 Ways to add all elements of list to set in python

How to add all elements of list to set in python ?

As we know a set in python is a built-in  data type which stores multiple unordered items in a single variable.

Example of a set

my_set = {10,20,30,40}

Where,

  • A set contains unique values.
  • All items placed inside { }.

Similarly, a list in python is a built-in  data type which is used to store items of different types.

Example of list

my_list = {30,40,50,60,70}

where,

  • A list contains different types of values integer, float, string etc.
  • All items placed inside [ ].

When we will add all the items of the list to set it will look like this

{10,20,30,40,50,60,70}

Here, all the items are unique after adding as because list contains unique elements.

Method-1 : Add all elements of a list to set using update( ) function

Set class provides an update( ) method with the help of which all elements of list can be added to set.

Syntax : set.update(sequences)
#Program :
    
#Represents a set
my_set = {10, 20, 30, 40}
#Represents a list
my_list = [30, 40, 50, 60, 70, 80]
# adding all elements in list to the set
my_set.update(my_list)
print('After adding list to set : ')
print(my_set)
Output :
After adding list to set : 
{10,20,30,40,50,60,70,80}

In the above program we just passed the list inside the update( ) method, the elements which are not present in set those got added and the elements which are present in set those got skipped as set contains only unique elements.

Method-2 : Add all elements of a list to set using add( ) function

Set class provides an add( ) method with the help of which all elements of list can be added to set.

Syntax : set.add(element)

But the thing is that, add( ) only accept single element inside that. So, if we will pass list in that it will give TypeError: unhashable type: ‘list’ as output.

So to avoid this error we can use for loop and pass one by one element of the list inside add( ) method.

#Program :

#Represents a set 
my_set = {10, 20, 30, 40} 
#Represents a list 
my_list = [30, 40, 50, 60, 70, 80] 
# adding all elements in list to the set 
# By iterating over all elements of list using for loop
for item in my_list:
    # adding each element to the set
    my_set.add(item)
print('After adding list to set : ') 
print(my_set)
Output : 
After adding list to set : 
{10,20,30,40,50,60,70,80}

Method-3 : Add a list to set using add() & union()

We can add content of two sets by using union( ) method.

Syntax : s.union(t)
#Program : 

#Represents a set 
my_set = {10, 20, 30, 40} 
#Represents a list 
my_list = [30, 40, 50, 60, 70, 80] 
#convert list to set
#then add contents two sets 
my_set = my_set.union(set(my_list)) 
print('After adding list to set : ') 
print(my_set)
Output : 
After adding list to set : 
{10,20,30,40,50,60,70,80}

Method-4 : Add all elements in a list to set using | operator

By creating union of 2 sets by using | operator , then we can add elements of two sets. So we have to convert our list to set by using | operator.

#Program :

#Represents a set 
my_set = {10, 20, 30, 40} 
#Represents a list 
my_list = [30, 40, 50, 60, 70, 80] 
# adding all elements in list to the set 
# by converting list to set 
# then get union of both the sets using | operator
my_set  |= set(my_list )

print('After adding list to set : ') 
print(my_set)
Output : 
After adding list to set : 
{10,20,30,40,50,60,70,80}

Method-5 : Add a list to set using |= and unpacking list to set

We will add the elements of list to set just like previous solution means we will convert list to set then we will add the elements by finding union of two sets.

But we will convert list to set by string literal and unpacking our lists elements inside it.

#Program : 

#Represents a set 
my_set = {10, 20, 30, 40} 
#Represents a list 
my_list = [30, 40, 50, 60, 70, 80] 
# adding all elements in list to the set 
# by converting list to set 
# then get union of both the sets using | operator 
# Unpacking elements and OR that with original set
my_set |= set(*my_list ) 
print('After adding list to set : ') 
print(my_set)
Output : 
After adding list to set : 
{10,20,30,40,50,60,70,80}

Add all elements from multiple lists to the set :

Suppose we have 2 different list then add the elements of both the list to set.

#Program : 

#Represents a set 
my_set = {10, 20, 30, 40} 

#Represents a list 
my_list1 = [30, 40, 50, 60, 70] 
my_list2= [80,90] 
# adding all elements in list to the set 
my_set.update(my_list1,my_list2) 
print('After adding list to set : ') 
print(my_set)
Output : 
After adding list to set : 
{10,20,30,40,50,60,70,80,90}

Python: Dictionary with Multiple Values per Key

How we can create a dictionary with multiple values per key in python.

In python a dictionary is one of the important datatype which is used to store data values in key : value pair. Generally keys and values are mapped one-to-one. But it is not impossible that we can not map multiple values to a single key. So in this article we will discuss how we can map multiple values per key in dictionary.

Syntax of dictionary :

dictionary_name = {key1: value1, key2: value2}

where,

  • key1, key2… represents keys in a dictionary. These keys can be a string, integer, tuple, etc. But keys needs to be unique.
  • value1, value2… represents values in dictionary. These values can be numbers, strings, list or list within a list etc.
  • key and value is separated by : symbol.
  • key-value pair symbol is separated by , symbol.

Example of a dictionary covid_case where multiple values are associated with single key.

covid_case = {"January": [1000,1500,2000], "February": [1100,1300,1500], "March":[2000,2200,2400] }

So, now let’s explore the concept how to add a key:value pair to dictionary in Python.

Create a dictionary with a list as the value :

Generally, when multiple values are mapped to a single key, then that dictionary is called as MultiDict. So, let’s see an example how in dictionary multiple values are mapped to a single key.

#Program :

#Multiple values mapped to single key
covid_case = {"January": [1000,1500,2000], "February": [1100,1300,1500], "March":[2000,2200,2400] }
#printing the multidict
print("Dictionary with multiple values per key :")
print(covid_case)
Output :
Dictionary with multiple values per key :
{"January": [1000,1500,2000], "February": [1100,1300,1500], "March":[2000,2200,2400] }

In this example string keys have taken in a dictionary where multiple integer values are mapped to single key.

Finding multiple values of a key in the dictionary :

Like how we created a dictionary with a list as a value, similar we can get a list as output also. Means it is possible to get multiple values of a key in dictionary. So, let’s see an example how we can get multiple values of a key as a list.

#Program :

#Multiple values mapped to single key
covid_case = {"January": [1000,1500,2000], "February": [1100,1300,1500], "March":[2000,2200,2400] }
#printing the multidict
print("Complete dictionary :")
print(covid_case)
#Getting the list(multiple values) at key February
output_list=covid_case["February"]
#printing the multiple values of key February
print("Multiple values of key 'February' :")
print(output_list)
Output :
Complete dictionary :
{"January": [1000,1500,2000], "February": [1100,1300,1500], "March":[2000,2200,2400] }
Multiple values of key 'February' :
[1100,1300,1500]

Append multiple values to a key in a dictionary :

It is easy to create a dictionary where multiple values are mapped to a single key. But the tricky part is appending multiple values where already multiple values are mapped to that key.

So there 2 cases may arise i.e

  1. The key is already present with multiple values and new values will be added in that key.
  2. The key is not present in the dictionary, so new key with multiple values will be appended to that dictionary.

CASE -1 : Key is already present in dictionary :

#Program :

#Multiple values mapped to single key
covid_case = {"January": [1000,1500,2000], "February": [1100,1300,1500], "March":[2000,2200,2400] }
#printing the multidict
print("Before append :")
print(covid_case)


# Append multiple values to a key in dictionary covid_case 
def add_values_to_key(temp_dict, key, list_of_values):
    if key not in temp_dict:
        temp_dict[key] = list()
    temp_dict[key].extend(list_of_values)
    return temp_dict
    
    
# Append multiple values for existing key 'March'
covid_case = add_values_to_key(covid_case, 'March', [2600, 2800])
#printing the multidict
print("After append :")
print(covid_case)
Output :
Before append :
{"January": [1000,1500,2000], "February": [1100,1300,1500], "March":[2000,2200,2400] }
After append :
{"January": [1000,1500,2000], "February": [1100,1300,1500], "March":[2000,2200,2400,2600,2800] }

CASE -2 : Key is not present in dictionary :

#Program :

#Multiple values mapped to single key
covid_case = {"January": [1000,1500,2000], "February": [1100,1300,1500], "March":[2000,2200,2400] }
#printing the multidict
print("Before append :")
print(covid_case)


# Append multiple values to a key in dictionary covid_case 
def add_values_to_key(temp_dict, key, list_of_values):
    if key not in temp_dict:
        temp_dict[key] = list()
    temp_dict[key].extend(list_of_values)
    return temp_dict
    
    
# Append multiple values for key 'April'
#As key 'April' is not present so new key with multiple values will be added
covid_case = add_values_to_key(covid_case, 'April', [3000, 3500])
#printing the multidict
print("after append :")
print(covid_case)
Output :
Before append :
{"January": [1000,1500,2000], "February": [1100,1300,1500], "March":[2000,2200,2400] }
After append :
{"January": [1000,1500,2000], "February": [1100,1300,1500], "March":[2000,2200,2400], "April":[3000,3500 }

Python: How to get first N characters in a string?

This article is about finding the first N characters of String where the N represents any number or int value.

How to get the first N characters in a String using Python

As we know in Python String is a sequence of characters where the index numbers are associated with each character.

For example : We have a String variable named String_value which contains a String Technology i.e

String_value = “Technology”

Where the sequence number/index of the first character starts with 0 and it goes on. Like

Index of character ‘T’ = 0

Index of character ‘e’ = 1

Index of character ‘c’ = 2

Index of character ‘h’ = 3

Index of character ‘n’ = 4

Index of character ‘o’ = 5

Index of character ‘l’  = 6

Index of character ‘o’ = 7

Index of character ‘g’ = 8

Index of character ‘y’ = 9

In Python, with the help of the [ ] (Subscript operator or Index Operator) any character of the string can be accessed just by passing the index number within it.

Like String_value[i] will return i-th character of the string.

For example, String_value[4] will return character ‘n’.

Program to get first character of the String :

#Program:

String_value = "Technology"
First_char = String_value[0]
print('First character of the string is', First_char)
Output : 
First character of the string is T

Here, just by passing index position 0 in the operator [ ], we fetched the first character of the string.

Note : Like that by passing any index position in this [ ] operator, we can get the corresponding character of the string.

But next we have to find first N characters simply means a substring we have to return from the original string. So lets know how to achieve that.

Program to get first N characters of the String :

In the above example we just passed a single index position inside the subscript operator, beside this, the subscript operator can also take a range too.

Syntax :String_VariableName [Start_IndexPosition : End_IndexPosition : Step_Size]

Where,

  • Start_IndexPosition : It represents the index position from where it will start fetching the characters. (Here the default value is 0)
  • End_IndexPosition : It represents the index position upto which it will fetch the characters.
  • Step_Size : It represents the step value means interval between the characters.  (Here the default value is 0)

So, to get the first N characters of the string, we have to pass 0 as start index and N as the end index i.e 

String_value[0 : N]

So, it will return characters starting from 0-th index upto n-1-th index. And here default Step_Size is 0.

So Let’s do the program by using this substring concept.

#Program :

String_value = "Technology"
First_char = String_value[0:4]
print('First 4 characters of the string is', First_char)
Output :
First 4 characters of the string is Tech

Need to concern about Index Error :

When we are using index operator [ ] , we need to be careful about the index that we are passing. Because if we pass the index which does not exist in the string then it will give an error “string index out of range”.

#Program :

String_value = "Technology"
#Passing 25th index which is not present in string
First_char = String_value[25]
print('25-th character of the string is', First_char)
Output :
string index out of range

Let’s overview the complete program again 

#Program :

#Asking for string input
String_value = input()
#Asking for a number i.e N-th value
N=int(input())
#This line prints first character of the string as index passed is 0
First_char = String_value[0]
#Printing the first character
print('First character of the string is', First_char)
#It will find the substring from 0-th index to N-1-th index
First_char = String_value[0 : N]
#Printing the first N-th characters
print('First N-th character of the string is', First_char)
Output :
Technology
4
First character of the string is T
First N-th character of the string is Tech

Python : How to Check if an item exists in list ?

How to Check if an item exists in list using Python?

In Python List is a most versatile datatype which stores multiple items in a single variable. All the items present inside a list are indexed where the first item is associated with the index position 0 (Zero). In this article we will discuss how to check whether the list contains a specific item or not. Let’s explore the concept in more detail.

Example of a List :

List_item = [ 'Bhubaneswar' , 'Mumbai' , 'Kolkatta' , 'Chennai' , 'Delhi' ]

So, our task is to check an item that is present in the list or not. Suppose we are looking for the item ‘Mumbai’ in List_item and it is present in the list but if we will look for the item ‘Goa’ that does not exist in the list named List_item.

There are multiple approaches available which can be used to achieve this. So, let’s discuss each approach one by one.

Method-1 : Checking if the item exists in the list using “in” operator

"in" operator in python can be used to check the item exists in the list or not. With the help of if condition it can check whether the item is present or not. If it is present in the list then it returns True and if it is not present in the list it returns False.

Syntax : item_name in list_name
#Program :

List_item = [ 'Bhubaneswar' , 'Mumbai' , 'Kolkatta' , 'Chennai' , 'Delhi' ]
#Checking an item which is present in the list
if 'Mumbai' in List_item:
    print('Item Mumbai is present')
else:
    print('Item Mumbai is not present')
#Checking an item which is not present in the list
if 'Goa' in List_item:
    print('Item Goa is present')
else:
    print('Item Goa is not present')
Output :
Item Mumbai is present
Item Goa is not present

Method-2 : Checking if the item exists in list using list.count() function

list.count() method gives the occurrence of an item in the list. Means if the item found at least once or more than that then the item is present if the item occurrence is zero then that item is not present in the list.

Synatx :  item_name.count(item)
#Program :

List_item = [ 'Bhubaneswar' , 'Mumbai' , 'Kolkatta' , 'Chennai' , 'Delhi' ]
#Checking an item which is present in the list
#Occurrence of Chennai is 1
if List_item.count('Chennai'):
    print('Item Chennai is present')
else:
    print('Item Chennai is not present')
#Checking an item which is not present in the list
#Occurrence of Pune is 1
if List_item.count('Pune'):
    print('Item Pune is present')
else:
    print('Item Pune is not present')
Output :
Item Chennai is present
Item Pune is not present

Method-3 : Checking if the item exists in list using any() function

Using any( ) function for checking a string is a most classical way of performing this task. With the help of any( ) function we can check if any item of given iterable is True or we can check for a match in a string with a match of each list item/element.

Syntax : any(condition)
Python :

List_item = [ 'Bhubaneswar' , 'Mumbai' , 'Kolkatta' , 'Chennai' , 'Delhi' ]

#Checking an item which is present in the list
#Checking any item whose length is 11 exist in the list or not
result = any(len(item) == 11 for item in List_item)
if result:
    print('Item Bhubaneswar is present')
else:
    print('Item bhubaneswar is not present')

#Checking an item which is not present in the list
#Checking any item whose length is 1 exist in the list or not
result = any(len(item) == 1 for item in List_item)
if result:
    print('Item found with length 1')
else:
    print('No Item found with length 1')
Output :
Item Bhubaneswar is present
No Item found with length 1

Method-4 : Checking if the item exists in list using ‘not in’ inverse operator

'not in' inverse operator in python is an inbuilt operator which returns True if the item is not present in the list and it returns False if the item is present in the list.

Syntax : item_name not in list_name
Program :

List_item = [ 'Bhubaneswar' , 'Mumbai' , 'Kolkatta' , 'Chennai' , 'Delhi' ] 
#Checking an item which is not present in the list
#It will result true because Goa is not present in list
if 'Goa' not in List_item: 
    print('True, Goa not in list') 
else :
    print('False, Goa is in list') 

#Checking an item which is present in the list 
#It will result false because Delhi is present in list
if 'Delhi' not in List_item: 
    print('True, Delhi not in list') 
else :
    print('False, Delhi is in list')
Output :
True, Goa not in list
False, Delhi is in list

Method-5 : Checking if the item exists in list using Naive method

The naive method is the most simplest way of checking the existance of an element as it iterates the through all the elements of the list. If the item found in the list then it return true.

#Program :

List_item = [ 'Bhubaneswar' , 'Mumbai' , 'Kolkatta' , 'Chennai' , 'Delhi' ] 
#Checking an item which is not present in the list
#It will result true because Kolkatta present in list

for i in List_item: 
    if i == 'Kolkatta':
        print("True")
Output :
True