Search code examples
pythonpython-3.xlistdictionarykeyvaluepair

How to extract values from list and store it as dictionary(key-value pair)?


I need to extract 2 values from this list of dictionary and store it as a key-value pair. Here I attached sample data..Where I need to extract "Name" and "Service" from this input and store it as a dictionary. Where "Name" is Key and corresponding "Service" is its value.

Input:

response  = {
'Roles': [
    {
        'Path': '/', 
        'Name': 'Heera', 
        'Age': '25', 
        'Policy': 'Policy1', 
        'Start_Month': 'January', 
        'PolicyDocument': 
            {
                'Date': '2012-10-17', 
                'Statement': [
                    {
                        'id': '', 
                        'RoleStatus': 'New_Joinee', 
                        'RoleType': {
                                'Service': 'Service1'
                                 }, 
                        'Action': ''
                    }
                ]
            }, 
        'Duration': 3600
    }, 
    {
        'Path': '/', 
        'Name': 'Prem', 
        'Age': '40', 
        'Policy': 'Policy2', 
        'Start_Month': 'April', 
        'PolicyDocument': 
            {
                'Date': '2018-11-27', 
                'Statement': [
                    {
                        'id': '', 
                        'RoleStatus': 'Senior', 
                        'RoleType': {
                                'Service': ''
                                 }, 
                        'Action': ''
                    }
                ]
            }, 
        'Duration': 2600
    }, 
    
    ]
}

From this input, I need output as a dictionary type.

Output Format: { Name : Service }

Output:

{ "Heera":"Service1","Prem" : " "}

My try:

Role_name =[]
response = {#INPUT WHICH I SPECIFIED ABOVE#}
roles = response['Roles']
for role in roles:
    Role_name.append(role['Name'])
print(Role_name)

I need to pair the name with its corresponding service. Any help would be really appreciable.

Thanks in advance.


Solution

  • You just have to write a long line which can reach till the key 'Service'. And you a syntax error in line Start_Month': 'January') and 'Start_Month': 'April'). You can't have one unclosed brackets. Fix it and run the following.

    This is the code:

    output_dict = {}
    for r in response['Roles']:
        output_dict[r["Name"]] = r['PolicyDocument']['Statement'][0]['RoleType']['Service']
    
    print(output_dict)
    

    Output:

    {'Heera': 'Service1', 'Prem': ''}