Python Forum

Full Version: unpack dict
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Giving the following example:
How can one unpack the dict

Current output:
Output:
Class: Wizard NAME Ralph AGE 20 SPELLS {'fireball': 10, 'firestorm': 15} NAME George AGE 20 SPELLS {'firestorm': 15, 'meteor': 30}
Target output

Output:
Class: Wizard NAME Ralph AGE 20 SPELLS: fireball: 10, firestorm: 15 NAME George AGE 20 SPELLS: firestorm: 15, meteor: 30
character.json
{
    "wizard": [
        {
            "name": "Ralph",
            "age": 20,
            "spells": {"fireball": 10, "firestorm": 15}
        },

        {
            "name": "George",
            "age": 20,
            "spells": {"firestorm": 15, "meteor": 30}
        }
    ]
}
import json
file = "character.json"

with open(file, 'r') as rfile:
    character = json.load(rfile)

for character_class, data in character.items():
    print(f'Class: {character_class.title()}')
    for stats in data:
        for key, value in stats.items():
            print(key.upper(), value)
        print()
I got this to work
import json
file = "character.json"

with open(file, 'r') as rfile:
    character = json.load(rfile)

for character_class, data in character.items():
    print(f'Class: {character_class.title()}')
    for stats in data:
        temp_list = []
        for key, value in stats.items():
            if isinstance(value, dict):
                for k, v in value.items():
                    temp_list.append(f'{k}: {v}')
                string = ', '.join(temp_list)
            else:
                string = value
            print(f'{key.upper()}: {string}')
        print()