Skip to main content

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.

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...

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 s...

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...