Skip to content
Advertisement

Python how to parse a list[dict] in python and convert values from nested dictionaries as keys

Need help in writing clean code , I have a yaml parsed output which looks like this :

yaml_output = [{'name' : 'alex', 'subjects' : {'maths' : ['grade_1', 'grade_2']}},
               {'name' : 'rio', 'subjects' : {'maths' : ['grade_3', 'grade_2'], 'science : ['grade_4', 'grade_6']}}]

I want it create a list of dictionaries with subjects as key and name of the students as value in a dictionary where grades are the keys.

desired_output = [{'maths' : {'grade_1' : ['alex'], 'grade_2' : ['alex', 'rio'], 'grade_3' : ['rio']}}, {'science' : {'grade_4' : ['rio'], 'grade_6' : ['rio']}

needs subjects as key and name of the students as value in a dictionary where grades are the keys.

new_dict = []
for dict in yaml_output:
  for k,v in dict:
    for i,j in dict['subjects']:
      if any(i in dict_list for dict_list in new_dict):
        dict_list[i].append(v)

Advertisement

Answer

You were close. Your for k,v loop is looking at the wrong data. You don’t want to look at ALL the keys, you want to unravel the subjects key and reference the “name” specifically.

yaml_output = [{'name' : 'alex', 'subjects' : {'maths' : ['grade_1', 'grade_2']}},
               {'name' : 'rio', 'subjects' : {'maths' : ['grade_3', 'grade_2'], 'science': ['grade_4', 'grade_6']}}]

out = dict()
for data in yaml_output:
    for k,v in data['subjects'].items():
        if k not in out:
            out[k] = {}
        for g in v:
            if g not in out[k]:
                out[k][g] = []
            out[k][g].append( data['name'] )
print(out)

Output:

{'maths': {'grade_1': ['alex'], 'grade_2': ['alex', 'rio'], 'grade_3': ['rio']}, 'science': {'grade_4': ['rio'], 'grade_6': ['rio']}}
9 People found this is helpful
Advertisement