[Knowledge Sharing] How to fetch data values using python & dhis2 api

This is continuation of [ Knowledge Sharing ] Basic Python usage for DHIS2 APIs - Part 1

Today we will discuss how to extract data values from a data set in below format using Python DHIS2 API
DE_ID, DE_Name, Period, OrgUnit, Value

Here is a runnable code where we extract Reproductive Health dataset values for organisation unit Ngelehun CHC for the period 202006 from play.dhis2.com

Step 1: Retrieves Data Element Id and Name and store it in a dictionary to access later to print
Step 2: Does the actual data fetching
Step 3: Iterate over datavalues and DE dictionary ( from step 1) & print

from dhis2 import Api
api = Api('play.dhis2.org/2.33.4', 'admin', 'district')

#Step 1: Query Data Elements Metadata and store to dictionary
#format : {id:name}

de_list = {}
r = api.get('dataElements?paging=false', params={'fields': 'id,name'})
de_data = r.json()

for de in de_data['dataElements']:
    de_list[de['id']]=de['name']



#Step 2: Query DataValueSets
t = api.get('dataValueSets', params={'dataSet': 'QX4ZTUbOt3a', 'period':'202006','orgUnit':'DiszpKrYNg8'})

dvalue_data=t.json()

#Step 3: Iterate over datavalues and de dictionary &  print
print ("DE_ID, DE_Name, Period, OrgUnit, Value")
for dvalue in dvalue_data['dataValues']:

    de_id=dvalue['dataElement']
    period=dvalue['period']
    org_unit=dvalue['orgUnit']
    value=dvalue['value']
    print (de_id,',',de_list[de_id],',',period,',',org_unit,',',value)
#Sample Output
#ID,Name,Period,Org Unit, Value
#DUTSJE8MGCw , TT2 doses given , 202006 , DiszpKrYNg8 , 2
#jWaNoH0X0Am , TT3 doses given , 202006 , DiszpKrYNg8 , 2
#jWaNoH0X0Am , TT3 doses given , 202006 , DiszpKrYNg8 , 1
#..