Skip to main content

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.

Comments

Popular posts from this blog

All about READ in RPGLE & Why we use it with SETLL/SETGT?

READ READ is one of the most used Opcodes in RPGLE. As the name suggests main purpose of this Opcode is to read a record from Database file. What are the different READ Opcodes? To list, Below are the five Opcodes.  READ - Read a Record READC - Read Next Changed Record READE - Read Equal Key Record READP - Read Prior Record READPE - Read Prior Equal Record We will see more about each of these later in this article. Before that, We will see a bit about SETLL/SETGT .  SETLL (Set Lower Limit) SETLL accepts Key Fields or Relative Record Number (RRN) as Search Arguments and positions the file at the Corresponding Record (or Next Record if exact match isn't found).  SETGT (Set Greater Than) SETGT accepts Key Fields or Relative Record Number (RRN) as Search Arguments and positions the file at the Next Record (Greater Than the Key value). Syntax: SETLL SEARCH-ARGUMENTS/KEYFIELDS FILENAME SETGT  SEARCH-ARGUMENTS/KEYFIELDS FILENAME One of the below can be passed as Search Arguments. Key Fiel

What we need to know about CHAIN (RPGLE) & How is it different from READ?

CHAIN READ & CHAIN, These are one of the most used (& useful) Opcodes by any RPG developer. These Opcodes are used to read a record from file. So, What's the difference between CHAIN & READ?   CHAIN operation retrieves a record based on the Key specified. It's more like Retrieving Random record from a Database file based on the Key fields.  READ operation reads the record currently pointed to from a Database file. There are multiple Opcodes that start with READ and all are used to read a record but with slight difference. We will see more about different Opcodes and How they are different from each other (and CHAIN) in another article. Few differences to note.  CHAIN requires Key fields to read a record where as READ would read the record currently pointed to (SETLL or SETGT are used to point a Record).  If there are multiple records with the same Key data, CHAIN would return the same record every time. READE can be used to read all the records with the specified Ke

Extract a portion of a Date/Time/Timestamp in RPGLE - IBM i

%SUBDT Extracting Year, Month, Day, Hour, Minutes, Seconds or Milli seconds of a given Date/Time/Timestamp is required most of the times.  This can be extracted easily by using %SUBDT. BIF name looks more similar to %SUBST which is used to extract a portion of string by passing from and two positions of the original string. Instead, We would need to pass a value (i.e., Date, Time or Timestamp ) and Unit (i.e., *YEARS, *MONTHS, *DAYS, *HOURS, *MINUTES, *SECONDS or *MSECONDS) to %SUBDT.  Valid unit should be passed for the type of the value passed. Below are the valid values for each type. Date - *DAYS, *MONTHS, *YEARS Time - *HOURS, *MINUTES, *SECONDS Timestamp - *DAYS, *MONTHS, *YEARS, *HOURS, *MINUTES, *SECONDS, *MSECONDS Syntax: %SUBDT(value : unit { : digits { : decpos} }) Value and Unit are the mandatory arguments.  Digits and Decimal positions are optional and can only be used with *SECONDS for Timestamp. We can either pass the full form for the unit or use the short form. Below i