The ease that comes with the python programming language is one of the reasons why it is a programmer’s favorite. It is now handling data, files, databases, or its vast community. There are several ways of storing single values elements in python. In this article, our focus is on storing data with some keys and values. We will see different ways to create objects as Python Key Value Pair.
What is Key-Value Pair in Python?
In python, we have several data types used to store single value elements. However, to access elements from those objects, we need to use an index which is their positional identity. Similarly, the key value pair represents data in the form of keys and values. Every value present in the object corresponds to a key. These keys are used to access values from the object. The object which stores these key value pairs is known as Dictionary. There are several ways to define a dictionary or add a new key-value pair in existing dictionary objects. Let’s see each of them one by one.
Example 1: Creating Dictionary Object
The first thing we need to understand is how to create a dictionary object for storing key value pairs. So, let’s see its syntax.
Syntax:
dict_object = { 'key1':'value1','key2':'value2',....}
Let’s see an example.
# Creating a dictionary
dict_object = {'a':10,'b':20,'c':30}
print(dict_object)
print(type(dict_object))
Output:
{'a': 10, 'b': 20, 'c': 30}
<class 'dict'>
Example 2: Creating Dynamic Dictionary Using Class
So, in the above example, we have seen how we can create a dictionary object. But, the problem with the above method is it is static. If we want runtime updation in the dictionary items, we must follow another approach. So, the following example demonstrates how we can create a class that accepts key value pairs and then feeds them into a dictionary object.
# Creating dictionary class
class CreateDictionary(dict):
def __init__(self):
self = dict()
# Function to add key:value
def add(self, key, value):
self[key] = value
# Creating dictionary object
dict_obj = CreateDictionary()
key = input("Enter key: ")
value = input("Enter value: ")
dict_obj.add(key,value)
print(dict_obj)
Output:
Enter key: a
Enter value: 30
{'a': '30'}
Explanation
So, in the above example, we first created a CreateDictionary class inherited from dict class. After that, we created a function inside it to add key value pair there. In the end, we initialized its object and passed the key and values as the argument.
Example 3: Update() Method to update Items in Dictionary Object
However, we can create and update a dictionary using the above method. Dict class has an update method used to add items in the dictionary object. We can use the technique in two ways.
- Either we pass another dictionary object as the argument of updaate method.
- Or, We assign the value to a variable and pass it as the argument. Name of the variable is stored as the key of the item.
# Creating dictionary object
dict_obj = {'a':'10', 'b':'20','c':'30'}
print("dict_obj before update ", dict_obj)
# adding dict1 (key3, key4 and key5) to dict
dict1 = {'d':'40', 'e':'50'}
dict_obj.update(dict1)
# by assigning
dict_obj.update(f ='60')
print("dict_obj after update",dict_obj)
Output:
dict_obj before update {'a': '10', 'b': '20', 'c': '30'}
dict_obj after update {'a': '10', 'b': '20', 'c': '30', 'd': '40', 'e': '50', 'f': '60'}
Example 4: Update Dictionary using Subscript Notation
Although the above-specified method for dictionary updation is easy to use, the subscript notation method is highly used by programmers to update the dictionary. It is one of the easiest ways to update a dictionary object. Let’s see an example to understand how we can do that.
# Creating dictionary object
dict_obj = {'a':'100', 'b':'200','c':'300'}
print("dict_obj before update ", dict_obj)
# using the subscript notation
# Dictionary_Name[New_Key_Name] = New_Key_Value
dict_obj['d'] = '400'
dict_obj['e'] = '500'
dict_obj['f'] = '600'
print("Updated Dict is: ", dict_obj)
Output:
dict_obj before update {'a': '100', 'b': '200', 'c': '300'}
Updated Dict is: {'a': '100', 'b': '200', 'c': '300', 'd': '400', 'e': '500', 'f': '600'}
Example 5: Key Value Pair Using ArgParse
#importing argparse module
import argparse
class KeyValue(argparse.Action):
def __call__( self , parser, namespace,
values, option_string = None):
setattr(namespace, self.dest, dict())
for value in values:
# split it into key and value
key, value = value.split('=')
# Adding it as dictionary
getattr(namespace, self.dest)[key] = value
# Initializing parser object
parser = argparse.ArgumentParser()
# adding an arguments
parser.add_argument('--kwargs',nargs='*',action = KeyValue)
#parsing arguments
args = parser.parse_args()
# show the dictionary
print(args.kwargs)
Explanation
In the above example, we first created a class that inherits from the agrparse class where we write a similar kind of code as explained in example 2 to add elements in the dictionary. Then we initialized an object for argparse.Argparser to hold the values of arguments from CLI. Then we added that element in the parser variable, parsed the arguments and had it in the args variable. And then printed the values of the dictionary.
Example 6: Adding Key Value Pair to CSV File
As we can read a CSV file in the form of a dictionary, we can also write it in a CSV file. We can do it in the following way.
import csv
with open('names.csv', 'w', newline='') as csvfile:
fieldnames = ['first_name', 'last_name']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'first_name': 'Jane', 'last_name': 'Mary'})
writer.writerow({'first_name': 'Tom', 'last_name': ''})
writer.writerow({'first_name': '', 'last_name': 'Sasha'})
Output:
name.csv file:
first_name,last_name
Jane,Mary
Tom,
,Sasha
Explanation
So, in the above example, we can see that we first created a CSV file using the “with” keyword. After that, we specified the field names that changed as the CSV file’s header. After that, we instantiate the object for dictwriter, which contains several functions to write into the CSV file. Then, we used writeheader() and writer() function to write our key value pair into the CSV File.
Example 6: Removing Key Value Pair from Dictionary
# Creating Dictionary object
dict_obj = {'a':'100', 'b':'200','c':'300','e':'400','f':'500','g':'600'}
print("dict_obj before delete ", dict_obj)
# Deleting element using del
del dict_obj['g']
print("dict_obj after delete using del ", dict_obj)
# Deleting element using pop method
dict_obj.pop('f')
print("dict_obj after delete using pop method ", dict_obj)
Output:
dict_obj before delete {'a': '100', 'b': '200', 'c': '300', 'e': '400', 'f': '500', 'g': '600'}
dict_obj after delete using del {'a': '100', 'b': '200', 'c': '300', 'e': '400', 'f': '500'}
dict_obj after delete using pop method {'a': '100', 'b': '200', 'c': '300', 'e': '400'}
Explanation
So, in the above example, we have seen how we can delete elements from dictionary objects. We have seen different methods of deleting elements by specifying keys inside the pop function or in the subscript of dict_obj while using the del keyword.
Example 7: Key Value Pair to Dataframe
We can also convert key value pairs into a dataframe table. To do that, we will use the following code. Let’s see that.
import pandas as pd
record1 = pd.Series({'i':'00','j':'01','k':'02','l':'03'})
record2 = pd.Series({'i':'10','j':'11','k':'12','l':'13'})
record3 = pd.Series({'i':'20','j':'21','k':'22','l':'23'})
record4 = pd.Series({'i':'30','j':'31','k':'32','l':'33'})
# Creating dataframe
df = pd.DataFrame([record1,record2,record3,record4],index = ['0','1','2','3'])
print(df)
Output:
i j k l
0 00 01 02 03
1 10 11 12 13
2 20 21 22 23
3 30 31 32 33
Explanation
We first need to convert a dictionary using the Series class to do that. After that, we passed the series objects into the DataFrame class as the argument. This will return a dataframe object which consists of a table of values we passed.
FAQs on Python Key Value Pair
To iterate over the key value pair, we will use the following code block.# Creating Dictionary object
dict_obj = {'a':'100', 'b':'200','c':'300','e':'400','f':'500','g':'600'}
for key,value in dict_obj.items():
print('{} = {}'.format(key,value))
We can do that by using the list comprehension method. Use the following block of code to do that.lst = [v for (k, v) in data.iteritems()]
To retrieve a value from a list of dictionaries we will first specify the index position of the dictionary and then key of the dictionary whose value we want. For e.g.,dict_obj = [{'a':'100', 'b':'200','c':'300','e':'400','f':'500','g':'600'},{'i':'00','j':'01','k':'02','l':'03'}]
print(dict_obj[0]['b'])
Conclusion
So, today in this article, we learned about key value pairs. We have seen different ways of initializing dictionary objects statically and dynamically. We have also seen how we can update elements in dictionary objects using different methods. I hope this article has helped you. Thank You.