top of page

PYTHON CODE: Key-Value Pairs | Python

A key-value pair is a set of two linked data items:

  • A key, which is a unique identifier for a particular item of dataset, and

  • The value, which is the value corresponding to that identifier.

Key-value pairs are more frequently used in lookup tables (for example, VLOOKUP in Excel)- were it looks for a particular value that user wants to look for in the dataset and populates the user required information corresponding to that lookup value.


Suppose, we have a table which consists of Partner's Name and their Age corresponding to their name.

To store this data in Python (known as creating Dictionary), we have to specify the Partner's Name (known as Key) in double quotes with their age (known as Value) separated by colon (":"). Remember that the entire data should be specified inside the open and close curly braces ("{ }") and are assigned to a dictionary name (say "partnerInfo") as shown below-

partnerInfo = {"John": 32, "Mike": 27, "Alice": 29, "Michael": 40, "Sarah": 38}

To find the age of any particular partner from the dictionary and print, we use the 'print()' command which will refer to the dictionary name ("partnerInfo") for the lookup value ("Alice") as shown below-

print(partnerInfo["Alice"])

User can also print both key and value of each item in the dictionary using FOR LOOP Statement by defining the Partner's Name (as "partnerName"); Age (as "partnerAge") followed by the dictionary name ("partnerInfo"). The FOR LOOP begins with the keyword "for" followed by the function name already defined by the user (in our example, "partnerName" & "partnerAge"). The code is basically saying- for 'each item' in the existing list 'do something' and that something will be defined in the next intended line (in our example, 'print()' command) as shown below-

for partnerName, partnerAge in partnerInfo.items():
  print(partnerName, partnerAge)
 

Disclaimer: We, in our example, only cover how to perform such functions and less focusing on the type of example we take. Our motive is to deliver the exact solution to the queries on "How To" in the most simplest way. Of course, the application of these function can be seen in our advanced modules with more complex examples and datasets.

 

Feel free to share your views and ask for models in the #comment section. If you like our content, please hit a #like button.

16 views0 comments

Comentários


bottom of page