Pages

Friday, January 29, 2021

What is the use of setdefault() method in Python

setdefault()

setdefault() method returns the value from the dictionary for the key passed if already present in the dictionary. If not already present, it inserts a new entry with the key and value passed (if not passed assigns 'None' by default). 

There are different ways to add new key to the dictionary and to retrieve the data present in the dictionary for a specified key. How is setdefault() different from these?

Let's take an example to understand the difference better.

E.g.:

When working with large data sets, It becomes essential to check if a key is present in the dictionary and insert a new key if not already present. 

Below is one way of doing this without using setdefault() method.
  • Check the data present in the dictionary by passing the key (with in the square brackets). 
  • Monitor for the Key Error by using try and except and assign the value to the specific key. 
Assign key to dictionary in Python

If we don't check for the existence of key in dictionary and directly assigns the data, it will override the current value present in the dictionary and may cause issue.

Before we see how to do this by using setdefault(), let's see the syntax and the arguments to be passed. 

Syntax:

dictionary_variable.setdefault(key, <value>)

setdefault() accepts two arguments and returns the value present in the dictionary.
  • key is mandatory. 
  • value (default value) is optional and is to be passed only if the specified value is to be inserted to the dictionary if the key is not already present. 
    • If the key is already present in the dictionary, value passed would have no impact. 
    • If the key is not present in the dictionary and the value is passed, new key and value would be inserted to the dictionary. 
    • If the key is not present and value is not passed, new key and default value 'None' would be inserted to the dictionary.
  • Return value would be the value present in the dictionary for the key passed. If the key is not already present, new entry will be added and then the value would be returned.
Let's have a look at the example now. 

setdefault method in Python

In the above example, 
  • Line - 3: Both key (4) and value ("FOUR") are passed and the key isn't already present in the dictionary. New entry will be added to the dictionary and the value passed would be returned.
  • Line - 5: Only key (5) is passed and the key isn't already present in the dictionary. New entry will be added to the dictionary with value 'None' and same would be returned. 
  • Line - 7: Both key (1) and value ("UPDATED") are passed and the key is present in the dictionary. Value passed would be ignored and the current value ("ONE") from the dictionary would be returned. 

There is one drawback of using setdefault(), An entry will be inserted to the dictionary (if not already present) even if that wasn't intended. 

So, this is to be used to retrieve the value present in the dictionary and to add (with default value) if not already present.


If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

Tuesday, January 26, 2021

Working with Sets in Python

Sets in Python

Set is a collection of data (of different data types) and is specified using curly brackets. 

Set is one of the Sequence data types in Python and has unique features compared to the other data types (list, tuple and dictionary).

Below are some of the features of Sets. 
  • Sets can hold data of different data types.
  • Data in the set can only be added or removed and cannot be amended.
  • Data in the set is unordered (i.e., every time a program is run, same data is stored in different order) and cannot be accessed by using index.
  • Duplicate data is not allowed in Sets.
In this post, we will see how to access, add or remove the data from sets and the use of different set methods. 

Creating a set in Python

Before we go on to different methods of a set, let us see How to create a set in Python.

A set is created when the data is assigned with in curly brackets (Unlike dictionaries, no key value would be present in Sets). 

Syntax:

new_set = {"Value1", "Value2",...}

Creating a set in Python

As I mentioned in the features, data is stores in no specific order and might vary between each run. Let's try running the above code twice and see how the data in the set is stored.

Result - 1:

Set in Python

Result - 2:

Set in Python

Creating a set by copying the data

Other way of creating a set is by copying the data from another set. This can be done by using the method copy(). This method doesn't accept any arguments.

Syntax:

new_set = old_set.copy()

Creating a set by copying data from the other set

In the above example, A set is created by by copying the data from another set which is already created. 

Set in Python

Accessing the data from a Set

Data in the set is neither indexed nor ordered. So, how do we access the data in a set? Specific value from set cannot be accessed as there is no index or key. But, Data in the set can be accessed by iterating in a loop.

Let's have a look at the example using for loop to access the data from a set. 

Access the data from a set in Python

In the above example, for loop is executed for each value present in the set. Again, the data in the set is stored in no specific order, so every time the program is run, sequence of the data returned could be different. 

Set in Python

Adding the data to a Set

Data present in the set cannot be amended. But, new data can be added by using the method 'add()'. This method accepts a single argument (i.e., data to be added). 

Syntax:

new_set.add("Data to be added")

Let's have a look at the example. 


In the above example, we are using add method twice.
  • Line - 4: We are adding "NEW" to the set. "NEW" is already present, so another entry won't be added in the set. Duplicate values aren't allowed. 
  • Line - 5: We are adding "NEW DATA" to the set. This would added to the set in no specific order.
If we print a set after adding the new data, Just like creating a set, data wouldn't be in specific order. 

Set in Python

Updating a set with data from another set

add() method is helpful if there is only one element that needs to be added to a set. If we need to add a set of values from another set, update() method is helpful to do this. This method accepts an iterable as an argument and adds each element in the iterable to the set. Data in the set passed as an argument won't be updated. 

Syntax:

set_one.update(set_two)

This can be easily understood with below example. 

Add data to set from the other set

In the above example, 
  • Line - 7: Passing the set as an argument to update method would add the data to 'set_one'. Any duplicate values will not be added. 
  • Line - 12: We are passing a string as an argument. Unlike, the add() method string won't be added to a set as is. update() method would consider the string as an iterable and adds each character as separate value in a set. 
Set in Python

Deleting the data from a Set

There are multiple methods to delete the data from a set. 
  • remove()
  • discard()
  • pop()
remove() method accepts the data that needs to be removed from a set. 

Syntax:

set_one.remove("Data to be removed")

Remove the data from a set in Python

Value passed in the argument would be removed from a set. If a value that is not present in the set is passed an exception will be thrown. 

Set in Python

Like remove() method, discard() method accepts an argument that needs to be removed from a set. 

set_one.remove("Data to be removed")

Remove the data from a set in Python


So, what's the difference between remove() and discard methods()? remove() method throws exception when the data that is not present in the set is passed. And, discard() method would ignore the exception if the data not present in a set is passed.

pop() method works in a different way compared to remove() and doesn't accept any argument. Data would be deleted from the set randomly and returns the data that is deleted. 

Syntax:

set_one.pop()

Remove data from a set using pop method

Data deleted in each call could be different as the data is stored in no specific order. 

Set in Python

There is one other way to delete the data from a set is by clearing the data from a set using the clear() method. This would clear all the data present in a set. 

Syntax:

set_one.clear()

Clear data from a set in Python

Union and Intersection of two sets

union() and intersection() are the two useful methods when working with two different sets. 

union() - accepts a set as an argument and returns the set with the data from both the referring sets (any duplicate data would only present once in the result).

Syntax:

new_set = set_one.union(set_two)

intersection() - accepts a set as an argument and returns the set with the data that is present in both the referring sets.

Syntax:

new_set = set_one.intersection(set_two)

With the use of above union and intersection methods, data from both the sets won't be affected. New set would be returned with the corresponding result.

There is one other method to do intersection is intersection_update(). This doesn't return a resulting set instead updates the calling set with the result. i.e., existing data from the set would be cleared and only common data between both the sets would be updated. 

Below example shows the use of all three methods. 

Union and Intersection of sets in Python

In the above example, 
  • Line - 7: union() method would return the data from both the sets and would be printed by print function. Both sets 'set_one' and 'set_two' won't be updated with this operation.
  • Line - 11: intersection() method would return the data that is common to both the sets and printed by print function. Both sets 'set_one' and 'set_two' won't be updated with this operation.
  • Line - 16: intersection_update() method would update the 'set_one' with the data that is present in both the sets 'set_one' and 'set_two'.
Set in Python

Relationship between two sets

While working with data, It becomes essential to check the relationship between different sets. Like, 
  • If a set is sub set of other set
  • If a set is super set of other set
  • If two sets are disjoint
Below methods are helpful achieve this. 

issubset()

This method checks if a set is a subset of the set passed in the argument and returns True if it is a subset and False if not a subset.

Syntax:

set_one.issubset(set_two)

issuperset()

This method checks if a set is a superset of the set passed in the argument and returns True if it is a superset and False if not a superset. 

Syntax:

set_one.issuperset(set_two)

isdisjoint()

This method checks if a set is disjoint of the set passed in the argument (i.e., no elements are common between both the sets).

Syntax:

set_one.isdisjoint(set_two)

Below is the simple example using these three methods. 

Subset, superset and disjoint in Python

Difference between two sets

Identifying the difference between two sets becomes essential when working with data. Below methods are helpful to retrieve the difference between the sets. 

difference()

Returns the data present in a set and not present in the set passed as an argument. Difference data would be returned as a set. None of the two sets would be updated by using this method. 

Syntax:

new_set = set_one.difference(set_two)

difference_update()

Updates a set with the data that is not present in set passed in the arguments. In other words, elements present in both the sets would be removed from the initial set. 

This method doesn't return any value.

Syntax:

set_one.difference_update(set_two)

Below is a simple example by using these two methods. 

Difference between two sets in Python

symmetric_difference()

difference() method would only return the data difference that is present in the set the method is associated with and ignores the data present in the set passed in the argument. 

symmetric_difference() method would consider both the sets and return the data by removing the common elements. In simple words this is like opposite of intersection. 

Syntax:

new_set = set_one.symmetric_difference(set_two)

symmetric_difference_update()

This method doesn't return a set instead updates the associated set with the data from both the sets after removing the common elements. 

Syntax:

set_one.symmetric_diiference_update(set_two)

Below is a simple example by using these two methods. 

Symmetric difference between sets in Python


Hope the above details were a bit of help to you in understanding more about Sets in Python.


If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

Sunday, January 17, 2021

Working with Dictionaries in Python - Contd.

Dictionaries

In the last post, I have explained how to create dictionary, add new values to the dictionary and remove the values from dictionary. 

We have also seen the below methods. 
  • setdefault() - Retrieve the data associated with the specific key passed. If key isn't present in the dictionary, new entry would be added. 
  • pop() - Returns the data associated with the key (passed) and deletes the entry from dictionary.
  • popitem() - Returns the last key and corresponding value from the dictionary. Accepts no parameters. 
Click Here to go through about these in detail.

We will see about some more methods associated with dictionaries in this post. 
  • keys() - Retrieve the keys present in the dictionary.
  • get() - Retrieve the value associated with the key passed. 
  • clear() - Clears the dictionary.
  • copy() - Copy the dictionary to other.
  • items() - Returns the items (key & value) present in the dictionary.
  • update() - Updates the dictionary with the elements from the other dictionary. 
  • values() - Returns the values present in the directory.
  • fromkeys() - Creates new dictionary from the values provided.
Let's have a look at these methods in detail by it's usage with an example.

Retrieve data from Dictionary

Depending on what data (Keys, Values or Both) we need to retrieve from the dictionary, we can use the below methods. 

If we need to retrieve the keys present in the dictionary, keys() method can be used to retrieve the keys.

Retrieve keys from a dictionary

keys() method can be used either to print all the keys at once (or assign it to a variable) or can be looped through in the for loop for each key value. 
  • In case of keys() in the print statement, all the keys would be printed once as type dict_keys.
  • In case of for loop, each key would be printed separately. 
Print the keys of a dictionary

If we need to retrieve the values from a dictionary, values() method can be used to retrieve the values. We will use the similar example as above to understand this easily. 

Retrieve values from a dictionary

values() method can be used either to print all the values at once (or assign it to a variable) or can be looped through in the for loop for each value. 
  • In case of values() in the print statement, all the values would be printed once as type dict_values.
  • In case of for loop, each value would be printed separately. 
Print values from a dictionary

Methods keys() and values() are helpful if we need to retrieve either keys or values separately. If we need to retrieve both the keys and values, items() method can be used. This method would return each key and value combination as a tuple. 

Retrieve data from dictionary

items() method can be used either to print all the items (key & value combination) at once (or assign it to a variable) or can be looped through in the for loop for each value. 
  • In case of items() in the print statement, all the values would be printed once as type dict_items.
  • In case of for loop, each key and value combination would be printed separately as a tuple.
Retrieve data from dictionary

Methods (keys(), values() and items()) explained above are helpful if we need to retrieve all the data present in the dictionary. We can use the method get(). This method accept key as an argument and returns the value. 

Retrieve data from dictionary for a specific key

This would print the value associated with the key (2) passed (i.e., "TWO"). 

Copy data from one dictionary to the other

There are couple of ways for copying data from one dictionary to the other. 
  • Copy (or append) the data from one dictionary to the other dictionary already created. 
  • Create the dictionary by copying the data from a dictionary. 
update() method is useful to copy the data from one dictionary to the other dictionary which is already created. This method accepts a dictionary as an argument and appends the data from this dictionary to the original dictionary. 

It can be easily understood with the below example. 

Copy data from one dictionary to the other

In the above example, data form dictionary 'b_dict' is appended to the dictionary 'a_dict'. Data in the dictionary 'b_dict' stay as is. 

Copy data from one dictionary to the other

If there is no dictionary is created already, New dictionary can be created by using copy() method and copy the data to the dictionary created. 

Copy data and create dictionary

Dictionary 'b_dict' would be created with the data from 'a_dict' and both dictionaries should hold same data at this point. Any new data added to 'a_dict' after this would not be reflected in 'b_dict'.

Creating a dictionary based on the keys from a List or Tuple

In the previous example, we have seen how to create a dictionary by copying the data from the other dictionary. 

Let's say we have a list of keys present in either List or Tuple and the value against these keys are same, fromkeys() method is useful in this scenario. 

E.g.: 

We have a list containing integers [1, 2, 3] and a tuple containing strings ("ONE", "TWO", "THREE") and we need to create the dictionary with a value 'int' for integers and 'str' for strings, instead of writing each key to the dictionary list or tuple can be passed. 

Create dictionary from the keys passed

Two dictionaries would be created with the same value for all the keys. 

Print dictionary in Python

Clear data from the dictionary

We can use the clear() method to clear the data from a dictionary. 

Clear data from the dictionary

Hope above details were a bit of help to understand more about Dictionaries. 


If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

Sunday, January 10, 2021

Working with Dictionaries in Python

Dictionaries

Dictionaries (dict) are used to store the data based on a key value. Unlike Lists and Tuples, data in the dictionaries isn't stored based on the index. And, data in the dictionaries are specified using curly brackets with the key and it's corresponding value ({key1 : value1, key2 : value2,...}

Below are some of the features of dictionaries in Python. 
  • Dictionaries can hold data of different data types.
  • Data in the Dictionary can be amended. 
  • Data in the Dictionary needs to be accessed by using the key.
  • No duplicate key values are allowed in Dictionary (duplicate data can be present with different key).

In this post, we will see how to access the data from dictionary, amend the data for a specific key value and different methods associated with dictionary. 

Creating a dictionary in Python

A dictionary is created when the data (and corresponding key value) in curly brackets is assigned to a variable.

Creating dictionary in Python

In the above example,
  • 1, 2, "THREE", "FOUR" and 5 are the keys. Key doesn't necessarily be numeric but should be unique with in dictionary. 
  • "ONE", "TWO", 3, 4 and True are the values against the corresponding keys. Dictionary can hold the data of different data types. 
  • A value will always have a key associated and can only be accessed by using the key.
We just stated that key should be unique with in dictionary. What happens if we mention duplicate keys with in dictionary? Value passed against the key will replace the original value in the dictionary and will not have duplicate keys in the final dictionary. It can be understood better using the below example.

Creating dictionary in Python

In the above example, 
  • Line - 2: Key '1' is specified twice to create 'a_dict' dictionary. Data stored in the dictionary will only have the latest value assigned against key '1' ("ONE - UPDATED").
  • Lines - 6 & 7: 'a_dict' is created without any duplicate values and data for key '1' is updated after dictionary is created. 
  • Both these dictionaries would return the same key and values. 
  • Line - 7: Data in the dictionary can be accessed or updated by mentioning it's key value with in square brackets.
Print dictionary in Python

Adding new data (and key) to Dictionary

There is no method like add() or append() to add a key (and data) to a dictionary. Like accessing or updating the data by using a key value, New key can be added by specifying new key with in square brackets and assigning data to it. 

dictionary_variable["new key"] = "New Data to be Added"

Adding new key to dictionary in Python

In the above example, Key '4' isn't specified when creating dictionary 'a_dict' (Line - 2). When the data is assigned to the new key (Line - 6), key is automatically added to the dictionary.

Dictionary in Python

There is one other way of adding data to the dictionary by using setdefault() method. setdefault() does more than just adding a new value, this can be easily understood with an example.

What is the use of setdefault method in Python

In the above example, 
  • Line - 6: We are passing new key and value to setdefault method. This would insert the new key and value into the dictionary and returns the value, so that the value can be printed.
  • Line - 12: We are passing the existing key with updated value. If the key already present in the dictionary, second argument has no affect in the operation. Data passed won't be updated and current data for the key is returned. 
  • Line - 17: We are passing new key with no value. As the key isn't present in the dictionary new entry will be written. No data is passed, so Python would add 'None' by default and returns the same.
print dictionary in Python

Removing the data (and key) from Dictionary

There are couple of methods 'pop()' and 'popitem()' to remove the data (and corresponding key) from the dictionary. Let's have a look at each of these methods. 

pop() - This method accepts the key as an argument and removes the corresponding value from dictionary. This method would also return the data that is being deleted.

Delete an item from the dictionary in Python

In the above example (Line - 7), pop() should remove the value "TWO" from the dictionary 'a_dict' and return the same, this would be printed to the console. print statement before and after this would show the dictionary before and after the data is removed from the dictionary. 

Remove data from the dictionary in Python

popitem() - This method works slightly different from pop(). This method doesn't accept any arguments and deletes the last value in the dictionary by default. Unlike pop(), popitem() returns both key and corresponding value (being deleted) as a tuple. 

Remove last value from the Dictionary in Python

In the above example (Line - 6), popitem() should remove the last item "THREE" and return both key (3) and value ("THREE") as a tuple. 

Print Dictionary in Python

We will have a look at some more dictionary methods in the next part.


If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

Sunday, January 3, 2021

Working with Tuples in Python

Tuple

Like an array, Tuple is a collection of data (of different data types). Tuples are specified using round brackets. 

Unlike Lists, Data in the tuple cannot be altered once a tuple is created. Below are some of the features of Tuples.  
  • Tuples can hold data of different data types. 
  • Tuples can not be amended.
  • Data in the tuple can be accessed by using index. Index of an element will remain same once defined.
  • Tuples can hold duplicate data. 

In this post, we will see how to access the data in Tuples and couple of tuple methods.

Creating a Tuple in Python

Like any other data type in Python, Tuple can be created by defining the data inside round brackets. 

Creating tuple in Python

Tuple can be created with data of different data types (or same type). 

In the above example,
  • 'a_tuple' is created with numeric data.
  • 'b_tuple' is created with character data.
  • 'c_tuple' is created with boolean data. 
  • 'd_tuple' is created with data of different data types.
All the tuples defined above has more than one element. Let's see how to define a tuple with just one element.  

Should it just be mentioning one element within round brackets? No, Just mentioning one element with in round brackets would consider the variable as the type of the data mentioned within round brackets. 

This can be easily understood with below example. 

Create tuple with just one element

In the above example, 
  • 'a_tuple' is defined just by mentioning a string with in round brackets. This wouldn't be considered as a tuple instead variable 'a_tuple' would be defined as a string.
  • 'b_tuple' is defined by mentioning comma (',') after the first element. This would define the variable as a tuple. 
print type of tuple

Accessing the data in a Tuple

Elements in a tuple can be accessed using index. Index starts with '0' and incremented by '1'.

Index for a tuple

Elements of a Tuple can be accessed from the last element with the negative index value. As we can see above, Index of last element would be '-1'. 

If we need to retrieve the second element ("TWO"), index '1' or '-4' needs to be mentioned within square brackets. 

E.g.: 

print(a_tuple[1]) #prints the second element of a list

print(a_tuple[-4]) #prints the fourth element from end of a list

In the above example, index is mentioned with in square brackets. Yes, Index needs to be mentioned with in square brackets for a tuple (not in round brackets like it is defined). 

Retrieve Index of an element

We have seen how to access the elements using an index, If we know the element and need to know the index, Method 'index()' would be helpful. One thing to note is, it always returns the first index if the element is present multiple times in the list. 

Retrieve index of an element in a tuple

In the above example, '2' is present twice in the list. But, only one index (first occurrence '1') will be returned.

Print list in Python

By using the index() method we would know the first occurrence of an element. Let's say if there are duplicate entries like in above example, we would need to pass the starting index along with the value. 

Retrieve index of an element in Tuple

In the above example (Line - 4), 'index(2, 2)' indicates to check for the value '2' (first argument) from the index '2' (second argument) and returns the index.


Count the number of occurrences

We have seen how to retrieve the index of an element. Let's say we are only interested in knowing how many times a value is present in the list (and not interested in the index), method 'count()' is helpful. 

Method 'count()' accepts the value to be checked as an arguments and returns the number of occurrences the data is present in a tuple. 

Count the number of occurrences in a Tuple

In the above example, '2' is present '3' times. So, count() should return '3'. 

print tuple

Hope the above details were a bit of help to you in understanding more about Tuples in Python.


If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

Exception Handling in Python (try - except-else-finally)

Exception Handling in Python Exception handling is key for any programming language. When an exception occurs Python interpreter stops execu...