Pages

Thursday, March 25, 2021

Dictionary Merge & Update Operators 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,...}. Click Here to see more about dictionaries. 

In this post, we will see more about the dictionary merge and update operators introduced in Python 3.9 along with the equivalent methods to do the same before 3.9.
 

Merge (|) Operator

Merge operator would merge the elements from both the dictionaries into a new dictionary. This wouldn't update either of these dictionaries. 

If there are any common keys between both the dictionaries only one would be present in the resulting dictionary as no duplicate keys are allowed in dictionaries.

Dictionary Merge Operator in Python

In the above example, 
  • Line - 5: merge (|) operator merges the elements from both the dictionaries (first_dictionary and second_dictionary) and adds the data to the result dictionary (new_dictionary).
      new_dictionary = first_dictionary | second_dictionary   

If there are duplicate keys in both the dictionaries, data from the second dictionary would be updated in the result dictionary.

Key value '3' has same value 'THREE', so we wouldn't know data from which dictionary the resulting data is from. Below example shows how the data is populated in the result dictionary.

Dictionary merge operator in Python

This operator is same as using {**d1, **d2} for merging dictionaries. 

Let's have a look at how merging works for merging the keys alone and both keys and values. 

Merge two dictionaries in Python

In the above example, 
  • Line - 5: Using single asterisk before the dictionaries inside curly brackets would merge the keys from both the dictionaries and returns a set. 
  • Line - 6: Using two asterisks before the dictionaries inside curly brackets would merge both the key and value and returns a dictionary. 

Update (|=) Operator

Update operator would append the elements from the dictionary on the right side to the dictionary on the left side.

By just using the merge operator, data in the dictionary can be updated as below. 

Update data in a dictionary in Python

In the above example, 
  • Line - 5: We are using merge operator to merge the data from the two dictionaries and assign the data to first_dictionary. 
Instead of using the merge operator, we can use update (|=) operator to do the same. 

Update data in a dictionary in Python

In the above example, 
  • Line - 5: We are using update (|=) operator to update the dictionary on the right side to the dictionary on the left side. And, data in the right side dictionary won't be updated. 
This is same as using dictionary update() method. 

Dictionary update method in Python

These operators make the dictionary merge and update operations easier.


Hope the above info was useful in understanding Dictionary Merge and Update operators. 


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

Saturday, March 20, 2021

Tuple Unpacking in Python

Tuple Unpacking

Tuple is a collections of data (of different data types) and are created by specifying the data (or variables) inside round brackets. We can also call this as Tuple packing. See more about working with tuples.

So, what is tuple unpacking? As the name suggests unpacking the data from a tuple into variables is called tuple unpacking.

Let's have a quick look at the creation of a tuple (packing) and unpacking of a tuple. 

Tuple unpacking in Python

In the above example, 
  • Line - 2: Creating variable num_one to store a number (1).
  • Line - 4: Creating variable char_one to store a string (ONE). 
  • Line - 8: Creating a tuple by mentioning the variables created inside round brackets (num_one, char_one). This can also be done by directly providing the data inside round brackets (1, "ONE").
  • Line - 11: Unpacking the tuple, unpacking the data in a tuple into different variables. First element in the tuple would be assigned to the first variable and second element in the tuple would be assigned to the second variable. 
  • Lines - 13 & 14: Printing the data from the unpacked variables.

We have not used round brackets to do the tuple unpacking. But, this should work in the same way even if we specify the variables inside round brackets for unpacking the data from a tuple. 

Tuple unpacking in Python

In the above example, we are unpacking a tuple with two elements to two different variables. Similarly, we can do the same for any number of equal variables. 

What to do if there are more number of elements in the tuple than the variables? 

Tuple unpacking would fail with "ValueError: too many values to unpack". 

Tuple unpacking in Python

Tuple Unpacking  - Value Error

So, how to deal with these kind of issues? Well, there isn't straight forward answer to this and depends on why we are moving more number of elements (from tuple) to a less number of variables. 

If this is intended and group of tuple elements should be assigned to a single variable (as list), this can be done by using asterisk (*) before the variable. 

Let's take a look at different example to understand this better. 

Tuple Unpacking in Python

In the above example, 
  • Tuple has three elements.
    • First element is the color. 
    • Second and Third elements are the fruits in the specific color. 
So the requirement here is to create a variable called 'color' to hold the color from tuple and create a list called 'fruits' to hold the list of fruits from tuple. 

If we use the variable names color and fruits as it is, ValueError would be thrown. So, we are using asterisk (*) before 'fruits' which needs to store the fruits as a list. 

Result here would be, 
  • Mapping of first variable to the first element (no asterisk for color, so would consider as one to one mapping). 
  • Mapping of second variable (list) to the remaining elements in the tuple. 
There are few points to consider here.
  • An empty list would be created if there is no corresponding data present in the tuple.     
Tuple unpacking in Python

  • A list would be created with just one element if there is only one corresponding entry in the tuple. Unlike the the variable with the type of data (if asterisk is not used).
Tuple unpacking in Python

  • A list would be created with multiple elements if there are multiple entries in the tuple. 
Tuple unpacking in Python

One thing to note here is a list variable doesn't necessarily be the second or last, this can be in any sequence. 

Let's take if we use asterisk before the color in the above example.

Tuple Unpacking in Python

color would be created as a list with the first two (or more if present) elements and fruits (str) would be created with the last element. 

We can only have one starred expression in an assignment.

Let's take another example with three variables. 

Tuple unpacking in Python

In this example, 
  • We are using three variables and given asterisk for the middle variable. 
  • First and Last elements in the tuple are assigned to the first and last variables. 
  • All other elements in the middle (from Tuple) are assigned as a list to the starred variable. 

Tuple unpacking would be helpful in many scenarios. We will have a look at how we can use tuple unpacking with dictionaries to unpack key and value from dictionary. 

Dictionary method items would return each key and value combination as a tuple. 

Tuple unpacking with dictionaries in Python

In the above example, for loop is repeated for every item (key and value) of a dictionary and the same would be returned as a tuple. 

Let's use tuple unpacking to unpack key and values.

Tuple unpacking with dictionaries in Python

Key and value are unpacked from tuple and can be used separately inside for loop. 

Hope the above info was useful in understanding Tuple unpacking in Python. 


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

Thursday, March 11, 2021

Using if-else statements in List Comprehension

List Comprehension

List comprehension is one of the ways of creating list. List would be created as a result of some operation on a range, set or list based on some condition (optional). Click Here to see more about list comprehension. 

In this post, we will see how to use if - else statements in list comprehension. 

Let's have a quick look at using if statement alone before we see if - else statements. 

E.g.: 

Create a list of odd numbers less than 10. 

odd_numbers = [number for number in range(10) if number % 2 != 0]

    In the above example, We are using if statement towards the end for identifying the odd numbers. 

    We are only considering the odd numbers using the if statement and leaving the others. But if we have to to a different operation for even numbers and different operation for odd numbers, we should be using if-else statements. 

    if-else statements in List Comprehension

    So, How do we use else statement in list comprehension? Is it just adding else statement after if condition? 

    Syntax wise it's a little different if we need to use both if and else statements. 

    Let's have a look at a simple example to understand this better. 

    E.g.: 

    Create a list with square of even numbers between 0 and 9 and just add "ODD" for every odd number between 0 and 9.

    This requires both if and else statements.

    result_list = 
    [number * number if number % 2 == 0 else "ODD" for number in range(10)]

    Let's breakdown the above statement into four parts. 
    • number * number indicates the expression that needs to be run if the condition is true and the resulting value is to be added to the list. This can be any expression as per the requirement. 
    • if number % 2 == 0 indicates the required if condition.
    • else "ODD" contains both the else statement and the value that needs to be added if the condition mentioned is False. Value here can be any expression as required. For example, We can use number * number if we need to calculate the square of odd number.
    • for number in range(10) indicates the for loop over an iterable. 

    So, syntax wise if - else statements in list comprehension would look like below.

    [expression if condition else expression for element in iterable]

    Key difference between using is if and if-else is the placement of these statements.
    • if statement is to be used at the end (i.e., after for) if no else statement is required. 
    • if - else statements are to be used at the beginning (i.e., before for) if else statement is required. 

    One thing to note is, List comprehension looks to be the easiest way of creating list. But, this can get more complicated and difficult to read and understand when we use it with multiple if (and else) and for statements. 



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

    Saturday, March 6, 2021

    If Condition in Python

    If Condition

    Conditions are nothing but statements used to check if a specific action is True or False. 

    In this post, we will see how If condition works in Python and how to use if, elif (Else-If) and else statements. 

    Syntax:

    if some_condition:
        // code to be executed
    elif another_condition:
        // code to be executed
    elif another_condition_2:
        // code to be executed
    .
    .
    .
    else:
        // code to be executed


    Let's breakdown the syntax of into three statements and see each of the statement in detail along with few examples.
    • if
    • elif
    • else

    if statement

    If statement is used to verify if a specific condition is True and the block of code under the if statement would only be executed if the condition is True. 

    if some_condition:
        // code to be executed

    'some_condition' here needs to be replaced with the actual condition to be used in the program and 'code to be executed' needs to be replaced with what needs to be executed when the condition is satisfied. 

    If the condition is not satisfied (In other words is False), code under the if condition would not be executed. 

    E.g.: 

    Check if a number is even and print "Even Number" if True. 

    if statement in Python

    In the above example, 
    • Line - 5: We are declaring the variable 'number' with the value 10 (even number).
    • Line - 6: We are using if statement to check if the result of number divided by 2 (modulus) is zero.
      • Here we are using Relational operator '==' to check if 'number % 2' is equal to '0'. Have a quick look at the different Relational operators.
    • Line - 7: print statement to print "Even Number". This statement would only be executed if the number is even. 
    If we are passing the number '11' instead of 10, modulus of 11 divided by 2 is '1' which is not equal to zero. 

    In this case code under if condition is not executed and no output would be printed. else statement would be helpful in these cases. 

    else statement

    else statement is used when we need to execute set of statements when the condition of the if statement becomes False. 

    if some_condition:
        // code to be executed
    else:
        // code to be executed

    code written under the else statement would only be executed if the condition on the if statement is False. 

    E.g.:

    Let's consider the same example of checking if the number is even. In the previous example, we aren't printing anything if the number passed is odd number.

    if - else statements in Python

    In the above example, 
    • Line - 6: We are declaring the variable 'number' with the value 11 (odd number).
    • Line - 7: We are using if statement to check if the result of number divided by 2 (modulus) is zero.
      • Here we are using Relational operator '==' to check if 'number % 2' (modulus) is equal to '0'. 
      • Modulus of 10 divided by 2 is '1', so condition is False.
    • Line - 8: print statement would not be executed as the condition is False. This statement would only be executed if the number is even.
    • Line - 9: else statement indicate the code to be executed if the condition is False. Following code under else would be executed.
    • Line - 10: print statement to print "Odd Number"
    *Code under if or else would be identified based on indentation. 

    This works perfectly fine if there is only one condition to be checked. However, If there are multiple conditions to be checked, we can use elif statement. 

    elif statement

    elif (Else If) statement is used when we have another (one or more) condition(s) to be verified before else statement if the condition on the if statement is false. We can have more than one elif statements. 

    if some_condition:
        // code to be executed
    elif another_condition:
        // code to be executed
    elif another_condition_2:
        // code to be executed
    .
    .
    .
    else:
        // code to be executed

    First elif statement would only be executed if the condition on the if statement is false, Second elif statement would only be executed if the condition on the previous elif statement is false and so on, else statement would only be executed if none of the if or elif statements are true.

    Let's have a look at simple example to understand if-elif-else statements better. 

    E.g.: 

    Identify the color and print the name of color. 

    if-elif-else statements in Python

    In the above example, 
    • Line - 9: We are declaring the variable 'color' with value 'Green'.
    • Line - 11: if statement with condition on color to check if 'White'. 
      • If True, code under the if statement would be executed (Line - 12). In this example result is False, so code under this statement would not be executed.
      • If False, condition on the next elif statement would be checked. 
    • Line - 14: elif statement with condition on color to check if 'Black'.
      • If True, code under the elif statement would be executed (Line - 15). In this example result is False, so code under this statement would not be executed. 
      • If False, condition on the next elif statement would be checked. 
    • Line - 17: another elif statement with condition on color to check if 'Green'.
      • If True, code under the elif statement would be executed (Line - 18). 
      • If False, code under the else statement would be executed. In this example result is True, so code under else statement would not be executed. 
    • Line - 20: else statement would only be executed if none of the above if and elif statements are True. 

    Nested if statements

    Nested if statements are having a if statement with in another if statement. 

    There is no limit on how many levels of nested if statements can be used. But, it is advised not to use too many nested if statements to make the program simple and easy to understand. 

    if some_condition:
        // code to be executed
        if nested_condition:
            // code to be executed
            .
            .
            .
        else:
            // code to be executed
        .
        .
        .
    else:
        // code to be executed

    Let's have a look at the simple example to understand this better. 

    E.g.: 

    Check if a number is between 0 and 9, If yes, check if the number is between 0 and 4.

    Nested if statements in Python

    In the above example,
    • Line - 3: We are declaring the variable 'number' with value '4'. 
    • Line - 6: if statement to check if the number is between 0 and 9. 
      • range(10) would return the numbers from 0 to 9 (both inclusive).
    • Line - 8: if statement with in the previous if statement (nested) to check if the number is between 0 and 4.
      • This if statement would only be executed if the condition on previous if statement is True. 
    • Line - 9: print statement would print "Number is between 0 and 4".
      • This would only be executed  the condition on the if statement is True (Line - 8).
    • Line - 11: else statement corresponding to the nested if statement.
      • print statement to print "Number is between 5 and 9" (Line - 12) under else statement. This would only be executed if the condition on corresponding if statement is False.
    • Line 14: else statement corresponding the original if statement.
      • print statement to print "Number is greater than or equal to 10" (Line - 15) under else statement. This would be executed if the condition on corresponding if statement is False.

    pass statement

    pass statement works more like a placeholder where some code is mandatory by syntax and no logic needs to be executed. 

    pass statement in if condition - Python

    In the above example, No logic needs to be executed if the number is even. Or, In other words, it is not yet finalized on what to be done. 

    In these cases, we can use pass statement as placeholder and continue with the program. 

    This can be replaced later if required or leave it as is if required. 


    Hope the above was a bit of help to understand the If conditions 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...