-1

I need to iterate following dict:

{'Tom': {'reading': ['excellent'], 'writing': ['B1', 'B2']}, 'Ben': {'reading': ['excellent'], 'writing': ['B2']}}

and write it in JSON file as:

{
'name': 'Tom'{
    'skills':'reading#excelent', 'writing#B1', 'writing#B2'
    }
'name': 'Ben'{
    'skills':'reading#excelent', 'writing#B1''
    }
}

Thanks for any advice.

Tried:

dict = {'name': '', 'skills': []}
for name, skills in persons.items():
    #print(name, skills)
    dict['name'] = name
    for skills, rate in skills.items():
        for tag in tag:
            rate = f'{skills}#{rate}'
            dict['skills'].append(rate)
            print(dict)
    
with open('vms1.json', 'w') as jfile:
    json.dump(dict, jfile, indent=2)

But all skills are applied to Ben

Cow
  • 2,543
  • 4
  • 13
  • 25
dilbar
  • 5
  • 2
  • 1
    Checking the provided JSON example with an [online validator](https://jsonformatter.curiousconcept.com/#) shows that it is invalid. Can you update the example with a valid one? – hwhap Aug 28 '23 at 11:02

1 Answers1

0

Here's your solution:

data = {
    'Tom': {'reading': ['excellent'], 'writing': ['B1', 'B2']},
    'Ben': {'reading': ['excellent'], 'writing': ['B2']}
}

output = []

for name, skills_dict in data.items():
    skills_list = []
    for skill, skills in skills_dict.items():
        skills_str = ', '.join(skills)
        skills_list.append(f'{skill}#{skills_str}')
    skills_str = ', '.join(skills_list)
    output.append(f"'name': '{name}'{{\n    'skills': '{skills_str}'\n}}")

result = ',\n'.join(output)
print(result)

Output:

'name': 'Tom'{
    'skills': 'reading#excellent, writing#B1, B2'
},
'name': 'Ben'{
    'skills': 'reading#excellent, writing#B2'
}
Musabbir Arrafi
  • 744
  • 4
  • 18