Python

numpy.append() – How to append Elements at the end of numpy array in Python

How to append elements at the end on a Numpy Array in python using numpy.append() in python ?

In this article we will discuss about how to append elements at the end on a Numpy array in python using numpy.append() method.

numpy.append() :

In python, numpy.append() is provided by Numpy module, by using which  we can append elements to the end of a Numpy Array.

Syntax : numpy.append(arr, values, axis=None)

where,

  • arr : refers to the numpy array where the values will be added.
  • values : refers to values that needs to be added.
  • axis : refers to axis along which values will be added to array where default value is None. If axis is None then values array will be flattened and values will be added to array. If axis is 0 then value add will occur row wise and if axis is 1 then value add will occur column wise.

Append elements at the end of 1D numpy array :

#Program

import numpy as np
# create a Numpy array from a list
arr = np.array([11, 22, 33])
#appending a single element to the numpy array
new_arr = np.append(arr, 88)
print(new_arr)
Output :
[11 22 33 88]

Append elements from a list to the Numpy array :

#Program 

import numpy as np 
# create a Numpy array from a list 
arr = np.array([11, 22, 33]) 
#appending multiple elements to the numpy array 
new_arr = np.append(arr, [66,77,88]) 
print(new_arr)
Output :
[11 22 33 66 77 88]

Flatten 2D Numpy Array and append items to it :

#Program 

import numpy as np 
# creating a 2D a Numpy array from a list 
arr = np.array( [ [11, 22, 23],
                [ 44, 55, 66] ])
#By flattening adding elements in List to 2D Numpy array 
new_arr = np.append(arr, [77,88,99]) 
print(new_arr)
Output :
[11 22 33 44 55 66 77 88 99]

Add a Numpy Array to another array row wise :

As we will add Numpy array to another array row wise then we have to set axis as 1=0.

So, let’s see an example how actually it works.

#Program 

import numpy as np
# Create two 2D Numpy Array like Matrix
matrix_array1 = np.array([[1, 2, 3],
                        [4, 5, 6]])
matrix_array2 = np.array([[7, 8, 9],
                         [11, 12, 13]])
 
#values will be added row wise as axis is 0                        
new_arr = np.append(matrix_array1, matrix_array2 , axis=0)
print(new_arr)
Output :
[[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
[11, 12, 13]]

Add a NumPy Array to another array – Column Wise :

As we will add Numpy array to another array row wise then we have to set axis as 1=0.

So, let’s see an example how actually it works.

#Program 

import numpy as np
# Create two 2D Numpy Array like Matrix
matrix_array1 = np.array([[1, 2, 3],
                        [4, 5, 6]])
matrix_array2 = np.array([[7, 8, 9],
                         [11, 12, 13]])
 
#values ill be added column wise as axis is 0                        
new_arr = np.append(matrix_array1, matrix_array2 , axis=1)
print(new_arr)
Output :
[[ 1 2 3 7 8 9]
[ 4 5 6 11 12 13]]

numpy.append() – How to append Elements at the end of numpy array in Python Read More »

Python Convert a 1D array to a 2D Numpy array or Matrix

Python: Convert a 1D array to a 2D Numpy array or Matrix

Python NumPy is the ultimate package in a python programming language that includes multidimensional array objects and a set of operations or routines to execute various operations on the array and process of the array. Where this numpy package is comprised of a function known as numpy.reshape() that performs converting a 1D array into a 2-D array of required dimensions (n x m). This function gives a new required shape without changing the data of the 1-D array.

This tutorial of Convert a 1D array to a 2D Numpy array or Matrix in Python helps programmers to learn the concept precisely and implement the logic in required situations. However, you can also learn how to construct the 2D array row-wise and column-wise, from a 1D array from this tutorial.

How to convert a 1D array to a 2D Numpy array or Matrix in Python

In this section, python learners will find the correct explanation on how to convert a 1D Numpy array to a 2D Numpy array or matric with the help of reshape() function.

One dimensional array contains elements only in one dimension.

program to convert a 1D array to a 2D Numpy array or Matrix in Python

Let’s try with an example:

#program

#import required libraries
import pandas as pd
import numpy as np
#create 1D numpy array
arr= np.array([2,3,1,8,6,4,7,0,9,5])
print(arr)
Output :
[2 3 1 8 6 4 7 0 9 5]

Now we will convert it into a 2D array of shape 5X2 i.e 5 rows and 2 columns like shown below:

[[0 1 2 3 4]
[5 6 7 8 9]]

Reshape 1D array to 2D array

First, import the numpy module,

import numpy as np

Program to Reshape 1D array to 2D array

Now to change the shape of the numpy array, we will use the reshape() function of the numpy module,

#Program:Reshape 1D array to 2D array

#import required libraries
import pandas as pd
import numpy as np
#create 1D numpy array
arr= np.array([2,3,1,8,6,4,7,0,9,5])
newarr = arr.reshape(5,2)
print(newarr)

Output:

[[2 3]
 [1 8]
 [6 4]
 [7 0]
 [9 5]]

First, we import the numpy module and then passed the 1D array as the first argument and the new shape i.e a tuple (5,2) as the second argument. It returned the 2D array.

Note: The new shape of the array must be compatible with the original shape of the input array, if not then it will raise ValueError.

numpy.reshape() function

  • It is used to give a new shape to an array without changing its data.
  • It returns the new view object(if possible, otherwise returns a copy) of the new shape.

Reshaped 2D array in view of a 1D array

If possible the function returns a view of the original and any modification in the view object will also affect the original input array.

Program to Reshaped 2D array in view of a 1D array

Example:

#Program:Reshaped 2D array in view of a 1D array

import pandas as pd
import numpy as np
arr_1 = np.array[2, 7, 5, 9, 1, 0, 8, 3]
arr_2 = np.reshape(arr_1, (2, 4))
aar_2[0][0] = 88
print(‘1D array:’)
print(arr_1)
print(‘2D array’)
print(arr_2)

Output:

1D array:
[88 7 5 9 1 0 8 3]
2D array:
[[88 7 5 9]
[ 1 0 8 3]]

Convert a 1D numpy array to a 3D numpy array using numpy.reshape()

In case, we have 12 elements in a 1D numpy array,

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

Program to Convert a 1D numpy array to a 3D numpy array using numpy.reshape()

Now, let’s convert this 1D numpy array to a 3D numpy array:

#Program:Convert a 1D numpy array to a 3D numpy array using numpy.reshape()

import pandas as pd
import numpy as np
arr = np.array([2,3,1,8,6,4,7,0,9,5,11,34])
arr_3 = np.reshape(arr,(2,2,3))
print(‘3D array:’)
print(arr_3)

Output:

3D array:
[[[2 3 1]
[8 6 4]]
[[7 0 9]
[5 11 34]]]

Here, the first argument is a 1D array and the second argument is the tuple (2, 2, 3).

It returned a 3D view of the passed array.

Convert 1D numpy array to a 2D numpy array along the column

After converting a 1D array to a 2D array or matrix in the above example, the items from the input array will be shown row-wise i.e.

  • 1st row of a 2D array was created from items at index 0 to 2 in the input array
  • 2nd row of a 2D array was created from items at index 3 to 5 in the input array
  • 3rd row of a 2D array was created from items at index 6 to 8 in the input array

Now suppose we want to convert a 2D array column-wise so we have to pass the order parameter as ‘F’ in the reshape() function.

Program to Convert 1D Numpy array to a 3D array with 2 matrices of shape 2X3

#Program:Convert 1D Numpy array to a 3D array with 2 matrices of shape 2X3

import pandas as pd 
import numpy as np
arr = np.array([2,3,1,8,6,4,7,0,9,5])
arr_2 = np.reshape(arr,(2,5),order=’F’)
print(‘2D numpy array’)
print(arr_2)
Output:
2D numpy array:
[[0 2 4 6 8]
 [1 3 5 7 9]]

Convert 2D array to 1D array as Copy

Suppose we want to create a 2D copy of the 1D numpy array then use the copy() function along with reshape() function.

Python Program to Convert 2D array to 1D array as Copy

Let’s try with an example:

#Program:Convert 2D array to 1D array as Copy

import pandas as pd 
import numpy as np
arr_1 = np.array[2, 7, 5, 9, 1, 0, 8, 3]
arr_2 = np.reshape(arr_1, (2, 4).copy())
#modify the 2D array that will not affect the original array
aar_2[0][0] = 88
print(‘1D array:’)
print(arr_1)
print(‘2D array’)
print(arr_2)

Output:

1D array:
[2 7 5 9 1 0 8 3]
2D array:
[[88 7 5 9]
 [ 1 0 8 3]]

Here, the 2D array is created of the 1D array. If you want to change the 2D array without changing the original array, just use the copy() function and the reshape() function.

Python: Convert a 1D array to a 2D Numpy array or Matrix Read More »

Python: Check if a list is empty or not

How to check if a list is empty or not in python ?

In this article we will discuss about different ways to check if a list is empty or not. 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.

Method-1 : Check if a list is empty using ‘not’ operator in python

A sequence object in python is implicitly convertible to bool. If the sequence is empty it will be evaluated to False else True. So just by using an if statement we can check the list is empty or not.

#Program :

# empty list created
my_list = []
# Here empty list object will evaluate to False
if not my_list:
    print('List is empty')
else:
    print('List is not empty')
Output :
List is empty

Method-2 : Check if list is empty using len() function

By using the len(), we can get the size of list. If the size of list is zero then it is empty list.

Example program :

#Program :

# empty list created
my_list = []

# Check if list's size is 0
if len(my_list) == 0:
    print('List is empty')
else:
    print('List is not empty')
Output :
List is empty

Method-3 : Check if list is empty by comparing with empty list

Empty list is denoted by [] this.  So by comparing our list object with [] , we can confirm the list is empty or not.

#Program :

# empty list created
my_list = []

# Check if list object points to literal []
if my_list == []:
    print('List is empty')
else:
    print('List is not empty')
Output :
List is empty

Method-4 : Check if list is empty using __len__()

We can get the size of list by calling __len__() function on the list object.  If the list size is equals to zero then the list is empty.

Let’s see an implementation of it.

#Program :

# empty list created
my_list = []

# Check if list's size is 0
if my_list.__len__() == 0:
    print('List is empty')
else:
    print('List is not empty')
Output :
List is empty

Method-5 : Check if a list is empty using numpy

First convert list inti Numpy array then check the size of Numpy array.

  • If the size of Numpy array is zero then the list is empty
  • If the size of Numpy array is greater than zero then list is not empty.

Let’s see an implementation of it.

#Program :

import numpy as np
# empty list created
list_of_num = []
arr = np.array(list_of_num)
if arr.size == 0:
    print('List is empty')
else:
    print('List is not empty')
Output :
List is empty

Python: Check if a list is empty or not Read More »

Python: Replace multiple characters in a string

How to replace multiple characters in a string in Python ?

In this article we will discuss about different ways to replace multiple characters in a string.

Suppose we have a String variable named my_string. So let’s see how we can replace its letters.

my_string = "You are studying from BTech Geek"

Now, we want to replace 3 characters of it i.e

  • ‘u’ will be replaced with ‘w’
  • ‘s’ will be replaced with ‘p’
  • ‘t’ will be replaced with ‘z’

Method-1 : Replacing multiple characters in a string using the replace() method

In python, the String class provides an inbuilt method replace()  which can be used to replace old character to new character. It replaces all occurrences of that character.

For example if we want to replace ‘a’ in a string to ‘b’ then at all the positions where ‘a’ is present those positions will be replaced with ‘b’ in the string.

Syntax : string_var_name.replace(old char, new char)

Now let’s see the implementation of it.

#Program :

#string 
my_string = "You are studying from BTech Geek"
char_to_replace = {'u': 'w',
                   's': 'p',
                   't': 'z'}
# Iterating over all key-value pairs in the dictionary
for key, value in char_to_replace.items():
    # Replacing matched key character with value character in string
    my_string = my_string.replace(key, value)
print(my_string)
Output :
Yow are pzwdying from BTech Geek

Method-2 : Replace multiple characters in a string using the translate ()

In python, the String class also provides an inbuilt method translate()  which can also be used like replace() to replace old character to new character. It replaces all occurrences of that character.

#Program :

#string 
my_string = "You are studying from BTech Geek"
char_to_replace = {'u': 'w',
                   's': 'p',
                   't': 'z'}
# Iterating over all key-value pairs in the dictionary
for key, value in char_to_replace.items():
    # Replacing matched key character with value character in string
    my_string = my_string.translate(str.maketrans(char_to_replace))
print(my_string)
Output : 
Yow are pzwdying from BTech Geek

Method-3 : Replacing multiple characters in a string using regex

regex module (re) in python provides a function sub() with the help of which we can also replace multiple characters of the string. Just we need to pass the pattern that we want to string.

#Program :

import re
#string 
my_string = "You are studying from BTech Geek"
char_to_replace = {'u': 'w',
                   's': 'p',
                   't': 'z'}
# Iterating over all key-value pairs in the dictionary
for key, value in char_to_replace.items():
    # Replacing characeters
    my_string = re.sub("[ust]",
                       lambda x: char_to_replace[x.group(0)],
                       my_string)
print(my_string)
Output : 
Yow are pzwdying from BTech Geek

Method-4 : Replacing multiple characters in a string using for loop

We can also replace multiple string in a string using for loop. It will iterate over the string character by6 character. When a matching character is found then it will replace the character with new character and will add to the string. If no replacement is found for that character then it ill add the character to the string.

For this we have to take a new string variable as the newly created string will stored in that new string variable.

Let’s see the implementation of it.

#Program :

#string 
my_string = "You are studying from BTech Geek"
char_to_replace = {'u': 'w',
                   's': 'p',
                   't': 'z'}
# Iterating over all key-value pairs in the dictionary
result_str = ''
# Iterating over all characters in string
for element in my_string:
    # Checking if character is in dict as key
    if element in char_to_replace:
        # If yes then it add the value of that char from dict to the new string
        result_str += char_to_replace[element]
    else:
        # If not then add the character in new string
        result_str += element
print(result_str)
Output : 
Yow are pzwdying from BTech Geek

Python: Replace multiple characters in a string Read More »

Python Dictionary: Values() Function

Python’s implementation of an associative array data structure is dictionaries. A dictionary is a collection of key/value pairs. A key pair and its associated value are used to represent each key pair.

A dictionary is a list of key-value pairs enclosed in curly braces and separated by commas. The column ‘:’ separates the value of each key.

Sorting a dictionary solely for the purpose of obtaining a representation of the sorted dictionary is not possible. By default, dictionary entries are ordered, but other data types, such as lists and tuples, are not. As a result, you’ll need an ordered data form, such as a list—probably a list of tuples.

Dictionary values() function & examples of it

values() is a built-in Python method that returns a list of all the values available in a given dictionary.

Syntax:

dictionary_name.values()

Parameters:

There is no need to pass parameters.

Return type:

It returns a sequence containing a view of all dictionary values. Because the sequence is just a view of values, any change to a value in the dictionary will be reflected in the sequence as well.

1)Display all the values of the dictionary

We can display all the values of the dictionary by using the given syntax above.

Implementation:

# given dictionary
dictionary = {'Hello': 700, 'This': 200, 'is': 100, 'BTechGeeks': 300}
# getting all the values from the given dictionary
dictvalues = dictionary.values()
# printing the values
print(dictvalues)

Output:

dict_values([700, 200, 100, 300])

2)Update/Modify the values of the dictionary

If we first fetch all of the dictionary’s values with the values() function and then modify the dictionary, the changes will be reflected in the sequence of the previously fetched values as well.

Below is the implementation:

# given dictionary
dictionary = {'Hello': 700, 'This': 200, 'is': 100, 'BTechGeeks': 300}
# getting all the values from the given dictionary
dictvalues = dictionary.values()
# print the values before modification
print("Before Modification", dictvalues)
# updating value of BTechGeeks to 1000
dictionary['BTechGeeks'] = 1000
# printing the after modification
print("After Modification", dictvalues)

Output:

Before Modification dict_values([700, 200, 100, 300])
After Modification dict_values([700, 200, 100, 1000])

3)Conversion of dictionary values to list

The sequence returned by the values() function can be passed to the list to create a list of all values in the dictionary .

We use list() function to achieve this

Below is the implementation:

# given dictionary
dictionary = {'Hello': 700, 'This': 200, 'is': 100, 'BTechGeeks': 300}
# getting all the values from the given dictionary and converting to list
dictvalues = list(dictionary.values())
# printing the dictionary values list
print(dictvalues)

Output:

[700, 200, 100, 300]

4)Display Maximum and minimum values

We can display maximum and minimum values by using max() and min() functions .

Below is the implementation:

# given dictionary
dictionary = {'Hello': 700, 'This': 200, 'is': 100, 'BTechGeeks': 300}
# getting all the values from the given dictionary and converting to list
dictvalues = dictionary.values()
# Getting max and min values
maxvalue = max(dictvalues)
minvalue = min(dictvalues)
# print the max value
print("Maximum value in dictionary", maxvalue)
print("Minimum value in dictionary", minvalue)

Output:

Maximum value in dictionary 700
Minimum value in dictionary 100

5)Display sum of dictionary values

We can display sum of dictionary values by using sum() function .

Below is the implementation:

# given dictionary
dictionary = {'Hello': 700, 'This': 200, 'is': 100, 'BTechGeeks': 300}
# getting all the values from the given dictionary and converting to list
dictvalues = dictionary.values()
# Getting sum of dictionary values
valuesum = sum(dictvalues)
# print sum of values
print("Sum of dictionary values", valuesum)

Output:

Sum of dictionary values 1300

6)Display Average of dictionary values

We can display average of dictionary values with the help of sum() and len() functions.

Below is the implementation:

# given dictionary
dictionary = {'Hello': 700, 'This': 200, 'is': 100, 'BTechGeeks': 300}
# getting all the values from the given dictionary and converting to list
dictvalues = dictionary.values()
# Getting average of dictionary values
averagevalue = sum(dictvalues)/len(dictvalues)
# print average of values
print("Average of dictionary values", averagevalue)

Output:

Average of dictionary values 325.0

Related Programs:

Python Dictionary: Values() Function Read More »

Pandas: How to create an empty DataFrame and append rows & columns to it in python

Methods to create an empty data frame and append rows and column to it

In this article, we discuss a dataframe how we can create an empty dataframe and after creating an empty dataframe how can we append rows and columns in it.

Before understanding this concept let us understand some basic concepts and terminologies.

Dataframe

Dataframe is a 2D data structure in python that store or represent the data in the 2D form or simply say in tabular form. The tabular form consists of rows, columns, and actual data. To create a dataframe or to use the dataframe we have to import the pandas package in our program.

As we cannot use dataframe without pandas let see what pandas in python are.

Pandas

Pandas is a package in python that is used to analyze data in a very easy way. The reason why pandas is so famous is that it is very easy to use. But we can not directly use the pandas package in our program. To use this package first we have to import it.

DataFrame()

This is the method that is widely used in this article. Let us take a brief about this method.DataFrame() is a constructor that is used to create dataframes in pandas.

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

Note:As we import pandas as pd in our program so we use pd.DataFrame() instead of pandas.DataFrame().

Now we see some theories and definitions related to pandas and dataframes let us see how we can practically implement it in our program.

In our dataframe definition, we see discuss that dataframe is consists of rows/index, columns, and data. Now think we want an empty dataframe that can be possible in 3 cases. First when there is no row and no column in the dataframe, Second when there is the only column and there when we have both rows and columns but the data value is NAN. Let us see these cases or methods one by one.

  • Method 1-Create an empty dataframe without any column and rows and then append them one by one

Let us see this method with the help of an example

import pandas as pd
df=pd.DataFrame()
print(df)

Output

Empty DataFrame
Columns: []
Index: []
Here we see that with the Dataframe() constructor we can easily create our dataframe. But our dataframe is empty as we didn’t pass any argument inside DataFrame() constructor. Now as we create our empty dataframe we can easily add columns and data to it. Let see how we can achieve this with the help of an example.
df['Name']=['Raj','Rahul','Aman']
df['Marks']=[100,98,77]
print(df)

Output

     Name  Marks
0    Raj    100
1  Rahul     98
2   Aman     77

Here Name and Marks are columns of the dataframe. Now, remember dictionary we can access and assign elements in a dictionary using a key similarly we done this task here but the pattern here is different.

  • Method 2-Create a dataframe with only a column and then append rows or indexes in it

Let us discuss this method with the help of an example.

df=pd.DataFrame(columns=['Name','Marks'])
print(df)

Output

Empty DataFrame
Columns: [Name, Marks]
Index: []

Here we see that we easily create empty dataframe bypassing columns in DataFrame() constructor. Now we have our columns so we can append rows/index in our dataframe using the append() method.

df = df.append({'Name' : 'Raj', 'Marks' : 100}, 
                ignore_index = True)
df = df.append({'Name' : 'Rahul', 'Marks' : 98},
                ignore_index = True)
df = df.append({'Name' : 'Aman', 'Marks' : 77},
               ignore_index = True)
print(df)

Output

     Name Marks
0    Raj   100
1  Rahul    98
2   Aman    77

Here we see if we have information about columns in the dataframe then we can easily add rows and data easily using the append() method. As the append() method does not change the actual dataframe so we assign the value returned by the .append() method in our original dataframe otherwise our dataframe will remain unchanged.

Note: append() method returns a new dataframe object

  • Method 3- Create an empty dataframe with column name and index/rows but no data

Let us see this method with the help of an example.

df=pd.DataFrame(columns=['Name','Marks'],index = [1,2,3])
print(df)

Output

  Name Marks
1  NaN   NaN
2  NaN   NaN
3  NaN   NaN

Here we see that we have created an empty dataframe that have both rows and column by simply passing column and index in DataFrame() constructor. Now we see how we can add data to it.

df.loc[1] = ['Raj', 100]
df.loc[2] = ['Rahul', 98]
df.loc[3] = ['Aman', 77]
print(df)

Output

      Name Marks
1    Raj   100
2  Rahul    98
3   Aman    77

If we have rows and indexes then we can add data in our dataframe using loc. loc is used to access groups of rows and columns by values.

So these are the methods to create an empty dataframe and add rows and columns to it.

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 – Creating Dataframe Objects:

Pandas: How to create an empty DataFrame and append rows & columns to it in python Read More »

Python : Join / Merge Two or More Dictionaries

Methods to merge two or more dictionaries in python

In this article, we discuss how to merge two or more dictionaries in python.

  • Method 1- Using update() method

Before understanding this let us understand how the update() method works in python.

Update() method in python

update() method is to update one of the dictionaries with the key and value of another dictionary. If the key is not present in one dictionary then that key will be added in the dictionary otherwise if the key is already present then that key-value pair is updated in the dictionary.

Syntax: d1.update(d2)

Let us understand this with the help of an example.

d1={"a":1,"b":2,"c":3,"e":5}
d2={"c":4,"f":6}
d1.update(d2)
print(d1)

Output

{'a': 1, 'b': 2, 'c': 4, 'e': 5, 'f': 6}

Explanation

In this example we see that key “c” is present in both d1 and d2 hence this value at this key is updated while other key-value normally add in the dictionary. The second thing we noticed that it is an in-place method that means no new dictionary is returned by the method and the changes are done in the dictionary itself.

We see that the update method easily merges two dictionaries. So this is how the update method work.

  • Method 2-Using **kwargs

Before understanding this method let us see how **kwargs works in python.

**Kwargs

**Kwargs in python means keyword argument i.e. is used to pass a keyworded, variable-length argument list. **  allows us to pass multiple arguments to a function. This argument creates a dictionary inside the function and then expands it. Let us understand this with an example.

d1={"a":1,"b":2,"c":3,"e":5}
d2={"c":4,"f":6}
d3={**d1,**d2}
print(d3)

Output

{'a': 1, 'b': 2, 'c': 4, 'e': 5, 'f': 6}

Explanation

**d1 & **d2 expanded the contents of both the dictionaries to a collection of key-value pairs.

d3={"a":1,"b":2,"c":3,"e":5,"c":4,"f":6}

This method work in this way. When we use ** with a dictionary it expands like this as shown above. Here we also see that key “c” is common in both the dictionary hence key-value pair of one dictionary gets updated with another dictionary.

Note: We can pass as many as an argument in this method.

d1={"a":1,"b":2,"c":3,"e":5}
d2={"c":4,"f":6}
d3={"g":7,"h":8}
d4={"i":9,"c":10,"k":11}
d5={**d1,**d2,**d3,**d4}
print(d5)

Output

{'a': 1, 'b': 2, 'c': 10, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'k': 11}

Here we pass 4 arguments and we get the perfect result. This is also one of the main advantages of this method.

So these are the methods to merge two or more dictionaries in python.

Problem with these methods and their solution

In all the method that we discussed till now, we have faced an issue that if the key we get in two or more dictionaries then the key-value get updated. This can be a major issue if we want to take account of all the key-value pairs in the dictionary. There is no specific method to solve this problem but with our knowledge of python programming, we can solve this issue and also make a user-defined method for this.

d1={"a":1,"b":2,"c":3,"e":5}
d2={"c":4,"f":6}
d3 = {**d1, **d2}
for key, value in d3.items():
    if key in d1 and key in d2:
        d3[key] = [value , d1[key]]
print(d3)

Output

{'a': 1, 'b': 2, 'c': [4, 3], 'e': 5, 'f': 6}

Explanation:

First, we de-serialize the contents of the dictionary to a collection of key/value pairs and store it in d3 as seen before. Then we traverse through the elements of the dictionary d3 and check if we get the same key multiple times. If yes then we can store them in the list and our work will be done.

Python : Join / Merge Two or More Dictionaries Read More »

Python Programming – Customizing Attribute Access

In this Page, We are Providing Python Programming – Customizing Attribute Access. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Customizing Attribute Access

Customizing attribute access

The following are some methods that can be defined to customize the meaning of attribute access for class instance.

object.___getattr____ ( self , name )
Called when an attribute lookup does not find the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception. Note that, if the attribute is found through the normal mechanism, ___getattr___ ( ) is not called.

>>> class HiddenMembers:
. . .        def ___getattr___ ( self , name ) :
. . .               return "You don't get to see "+name
. . . 
>>> h=HiddenMembers ( )
>>> h . anything
" You don't get to see anything "

object . setattr ( self , name , value )
Called when an attribute assignment is attempted. The name is the attribute name and value is the value to be assigned to if. Each class, of course, comes with a default ___setattr___ , which simply set the value of the variable, but that can be overridden.

>>> class Unchangable: 
. . .         def ___setattr____ ( self , name , value ) :
. . .                print " Nice try "
. . . 
>>> u=Unchangable ( )
>>> u . x=9 
Nice try 
>>> u . x
Traceback ( most recent call last ) :
    File "<stdin>", line 1, in ?
AttributeError: Unchangable instance has no attribute 'x' ;

object.___delattr___ ( self , name )
Like ____setattr___ ( ), but for attribute deletion instead of assignment. This should only be implemented if del ob j . name is meaningful for the object.

>>> Class Permanent :
. . . def ___delattr____ ( self , name ) :
. . . print name , " cannot be deleted "
. . .
>>> p=Permanent ( )
>>> p . x=9 
>>> del p . x 
x cannot be deleted 
>>> p . x
9

Python Programming – Customizing Attribute Access Read More »

Python Programming – Pre-Defined Attributes

In this Page, We are Providing Python Programming – Pre-Defined Attributes. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Pre-Defined Attributes

Pre-defined attributes

Class and class instance objects has some pre-defined attributes:

Class object

Some pre-defined attributes of class object are:

__name__
This attribute give the class name.

>>> MYClass . __name__
' MYClass '

__module__
This attribute give the module name.in which the class was defined.

>>> MYClass . ___module___
' ___main___ '

___dict___
A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g., MyClass . i is translated to MyClass .___dict___ [ ” i ” ].

>>> MyClass.___dict___
{ ' i ' : 12345 , '___module___' : '___main___ ' , '___doc___ ': ' A simple example class ' , ' f ' : <function f at 0x0640A070>}

___bases___
This attribute give the tuple (possibly empty or a singleton) containing the base classes.

>>> MyClass.___bases___.
( )

___doc___
This attribute give the class documentation string, or None, if not defined.

>>> MyClass.___doc___ 
' A simple example class '

Class instance object
Some pre-defined attributes of class instance object are:

___dict___
This give attribute dictionary of class instance.

>>> x. ___dict___ 
{ }

___class___
This give the instance’s class.

>>> x. ___class____ 
<class ___main___ .MyClass at 0x063DA880>

Python Programming – Pre-Defined Attributes Read More »

Python Programming – Instance Object

In this Page, We are Providing Python Programming – Instance Object. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Instance Object

Instance object

The only operation that done using class instance object x is attribute references. There are two kinds of valid attribute names: “data attribute” and “method”.

Data attribute corresponds to a variable of a class instance. Data attributes need not be declared; like local variables, they, spring into existence when they are first assigned to. For example, if x is the instance of MyClass (created, before), the following piece of code will print the value 16, without leaving a trace:

>>> x . counter=1
>>> while x . counter<10:
. . . x . counter=x. counter*2
. . .
>>> print x . counter 
16 
>>> del x . counter

The other kind of instance attribute reference is a method. Any function object that is a class attribute defines a method for instances of that class. So, x. f is a valid method reference, since MyClass. f is a function.

Python Programming – Instance Object Read More »