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

RPG's new Built-in Function %LIST and New Operation Code FOR-EACH - IBM i

RPGLE

RPG is the primary programming language for development on IBM i. And, IBM continues to provide enhancements to RPG. 

In this post, we will see couple of recent additions to RPG. 
  • Built-in Function %LIST
  • Operation Code FOR-EACH
Click Here to read my previous post on new BIF %RANGE and Operator IN. 

%LIST

New Built-in Function %LIST provides an easy way to populate the data into an array. %LIST accepts list of values and returns a temporary array.

%LIST can be directly used where arrays are allowed. This provides an option to developer to use %LIST instead of having to create an array where ever possible. There are some exceptions to this, %LIST cannot be used with SORTA (Sort an Array), %LOOKUP and %SUBARR. 

Syntax:

%LIST(item1 : item2 : item3 : ...) 

Below are some of the important points to note while working with %LIST. 
  • Minimum of one operand to be passed. 
  • All Operands must be of same type (like, %LIST with only numeric values or %LIST with only Character values. Not both the types at the same time). 
  • Arrays or Data structures cannot be passed as operands.
  • If assigning data to an array, Defined array should be of same data type as the data passed. 
%LIST can be used in the new FOR-EACH loop or in IF conditions using new Operator IN. 

FOR-EACH (For Each)

New Operation code FOR-EACH provides an easier way to iterate through an array, Subarray (using %SUBARR) or temporary array (using %LIST).

FOR-EACH Opcode begins a loop and ENDFOR to end the loop. 

Syntax:

FOR-EACH(H) item IN Array(or %SUBARR or %LIST)

Below are some of the important points to note while working with FOR-EACH.
  • Extender 'H' can be used to half adjust the numeric values.
  • First Operand cannot be an array. 
  • Data type of the first operand should match with the data type of an array, sub array or list. 
  • First operand can be a data structure. But, second operand should be related to the first operand by using LIKEDS.
We will see an example using both %LIST and FOR-EACH to understand better. 

New BIF %LIST and Opcode FOR-EACH in RPGLE - IBM i

In the above example, 
  • Line - 8: %LIST with the list of colours (character) returns a temporary array and assigns the data to the array already created. 
  • Line - 13: FOR-EACH Opcode would loop through the array 'wFavoriteColours' (second operand). Loop is repeated for each element in the array and data can be accessed using 'wColour' (first operand) inside the loop. Variable used in the first operand needs to be defined already. 
  • Line - 17: FOR-EACH Opcode would loop through the list of values provided using %LIST (with out having to define array). 
  • Line - 22: FOR-EACH Opcode would loop through the list of numeric values provided using %LIST. 
  • Line - 28: FOR-EACH Opcode would loop through the part of the array using %SUBARR. 
We are only using arrays in the above example. Below is a simple example showing how FOR-EACH loop can be used with Data structures. 

FOR-EACH loop with Data structures in RPGLE - IBM i


Hope the above info was a bit of help to understand %LIST and FOR-EACH better. 


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

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.

Tuesday, January 19, 2021

RPG's new Built-In Function %RANGE and new Operator IN - IBM i

RPGLE

Keeping the debate aside on whether the RPG is a dead programming language, Most of the recent surveys showed RPG is the primary program language for development on IBM i.

And, IBM continues to provide enhancements to RPG. In this post, we will see couple of recent additions to RPG. 
  • Built-in Function %RANGE
  • Operator IN

%RANGE

In SQL, we often use BETWEEN - AND in WHERE condition to check if a value is present in a particular range (specified using BETWEEN - AND). 

%RANGE BIF (Built-In Function) works in a similar way and used to check if a value is present in a particular range. This can be used to compare the data of any data type (and data we are comparing should be of same data type as the data mentioned in the RANGE)

Syntax:

%RANGE(lower-limit : upper-limit) ;

%RANGE accepts two arguments - Lower limit and Upper limit. Both Lower limit and Upper limit would be considered. 

%RANGE doesn't return any value and should always be used with operator 'IN'.

IN

IN operator is used to check if a value is present in the list of values provided. The list here can be, 
  • An array.
  • Range of values specified in %RANGE.
  • List of values specified using % LIST.
IN operator returns '1' if the value provided is present in the list and '0' if the value isn't present. 

Syntax:

x IN y

This can be used with in IF condition or DOW loop.

We will see an example using both %RANGE and IN to understand better. 

RPG's new BIF %RANGE and new Operator IN

In the above example, 
  • Line - 6: 'IN' operator is used to verify if Packed decimal value 'wNumber' is present in the range between 1 and 15. 
  • Line - 10: 'IN' operator is used to verify if Character value 'wString' is present in the range between 'AA' and 'AB'. 
    • Character value cannot be compared by specifying decimal values in %RANGE and vice-versa.
  • Line - 14: 'IN' operator is used to check the condition on DOW loop. 

Hope the above info was a bit of help to understand %RANGE and IN better. 


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.

Tuesday, January 12, 2021

Display Journal from SQL - IBM i

Display Journal

Journals play very important role on IBM i and are helpful to identify who has updated the data and/or to retrieve the data before the update or delete from the tables and so on. 

Data from the journals can be retrieved by using DSPJRN command. One other way of retrieving the data from journals is by using SQL table function DISPLAY_JOURNAL. Data returned from this function is similar to the data returned by DSPJRN command. 

We will see few examples to see how DISPLAY_JOURNAL works. 

Display Journal on IBM i


In the above example, 
  • We are passing two mandatory parameters Journal Name and Library.
    • 'JOURNAL_NAME' - Name of the Journal.
    • 'JOURNAL_LIBRARY' - Name of the Library Journal is present in.
  • Below are the few columns we are retrieving from Journal. This function returns much more data and full list can be found in this link on IBM Knowledge center. 
    • 'ENTRY_TIMESTAMP' - Time when the Journal entry was captured (E.g.: Time when the data was written, updated or deleted).
    • 'JOURNAL_ENTRY_TYPE' - Returns the type of Journal entry.
    • 'COUNT_OR_RRN' - Returns the RRN of the data in the Physical file.
    • 'OBJECT' - Returns the Object details. Object Name and Library Name (and Member Name for files).
    • 'OBJECT_TYPE' - Returns the Object type. 
    • 'ENTRY_DATA' - Data Captured in the Journal. This field of type 'BLOB' (Binary Large OBject).
Display Journal on IBM i

Looking at the above result, 'ENTRY_DATA' is displayed as HEX values. This needs to be converted to the required data type. 

In the above example, we are only passing Journal Name and Library as the parameters and query returns all the data that is present in the current journal receiver. This is fine because I am using test journal. 

However, this becomes extremely difficult in any real applications as there would be many objects added to the Journal and query may take large time to process. It is best to pass the as much information as possible in the parameters so that query can return the specific results and can run faster. 

In the below example, we will pass the specific file name and journal entry type as parameters and cast the 'ENTRY_DATA' to return the data as character.

Display Journal on IBM i


In this example, we are converting the Entry data to character format and passing parameters to select the data for a specific file, journal entry types with in specified time range. 

  • Converting (CAST) the ENTRY_DATA from BLOB to character (VARCHAR) format.
    • In the above query, we are using 'CAST' two times to convert the data to character format. 
    • With just one CAST statement "CAST(ENTRY_DATA AS VARCHAR(50) CCSID 37) AS JOURNAL_DATA", Character conversion between CCSID 65535 and CCSID 37 not valid.
    • So, we are first converting the data as character and using another CAST to change the CCSID.

  • We are passing more number of parameters here (compared to the previous example) so that results can be specific. Below are some of the additional parameters we are passing.
    • OBJECT_NAME - Name of the object we are retrieving the data for.
    • OBJECT_LIBRARY - Name of the library object is present in. Special values '*LIBL', '*CURLIB' can be specified as well.
    • OBJECT_OBJTYPE - Type of the object passed (like *FILE, *DTAQ, *DTAARA or *LIB).  
    • OBJECT_MEMBER - Name of the member, this is only required for Object Type '*FILE'. Special values like '*ALL', '*FIRST' or '*NONE' can be specified as well. 
    • JOURNAL_ENTRY_TYPES - Journal entry types we are retrieving the data for. Multiple entries can be specified by separating them with space.
    • STARTING_RECEIVER_NAME - Name of the starting journal receiver name. Special values like '*CURRENT', '*CURCHAIN' or '*CURAVLCHN' can be specified as well. If no value is specified '*CURRENT' is considered by default. 
    • STARTING_TIMESTAMP & ENDING_TIMESTAMP - Starting and Ending timestamps to retrieve the data from Journal.
    • There are many other parameters that can be specified to narrow down the results.
Display Journal on IBM i

Above example is perfectly suited for a table with just one character field. We will see another example for a table with decimal field. 

Display Journal on IBM i

In this query, we are converting the data for each field separately by taking the substring using CAST & INTERPRET*.
  • In this example, we are retrieving the data for a table with two character fields (Order Number & Customer Name) and one decimal field (Order Value).
  • Lines 4 - 8: CAST function to convert the substring of BLOB to character and INTERPRET function to make sure the query will return the data in the required format for both the character fields.
  • Lines 10 - 11: CAST function to convert the substring of BLOB to character and INTERPRET function to interpret the data as packed decimal value from the character value.
    • Packed decimal field (5, 2) would only have the buffer length of 3 digits. So, we are taking the substring of 3 digits and converting it as character. 
    • Interpret function would convert the 3 digits as the packed decimal value of (5, 2). 
Display Journal on IBM i

*INTERPRET function is only available since IBM i 7.3 (TR8) and IBM i 7.3 (TR2). For the previous versions we can continue to use CAST. But, CAST wouldn't convert the data as packed decimal.

Display Journal on IBM i

This would display the decimal value as character only (suffixed with 'F') and doesn't show the period (.) to differentiate decimal values. 

Display Journal on IBM i


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.

Different Ways of Sorting Data in a List - Python

Sorting Data in a List List is a collection of data (of different data types), much like an array. Like any data structure or data set, dat...