Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
unpack dict
#1
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 welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply


Messages In This Thread
unpack dict - by menator01 - Apr-09-2022, 02:18 PM
RE: unpack dict - by menator01 - Apr-09-2022, 03:10 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Too much values to unpack actualpy 3 536 Feb-11-2024, 05:38 PM
Last Post: deanhystad
  ValueError: not enough values to unpack (expected 4, got 1) vlearner 2 6,401 Jan-28-2022, 06:36 PM
Last Post: deanhystad
  [SOLVED] [geopy] "ValueError: too many values to unpack (expected 2)" Winfried 2 2,921 Mar-30-2021, 07:01 PM
Last Post: Winfried
  Cannot unpack non-iterable NoneType object, i would like to ask for help on this. Jadiac 3 9,007 Oct-18-2020, 02:11 PM
Last Post: Jadiac
  subprogram issues: cannot unpack non-iterable function object error djwilson0495 13 6,113 Aug-20-2020, 05:53 PM
Last Post: deanhystad
  struct.unpack failed Roro 2 3,408 Jun-13-2020, 05:28 PM
Last Post: DreamingInsanity
  Can't unpack values of dictionary with ** Snake 3 3,636 Mar-11-2020, 11:17 AM
Last Post: Snake
  Error: too many values to unpack Mike 1 5,167 Oct-30-2019, 03:07 PM
Last Post: buran
  How to unpack tuples in if statements saurkkum 1 5,217 May-05-2019, 09:43 AM
Last Post: Gribouillis
  too many values to unpack error fyec 1 8,090 Jun-28-2018, 01:48 AM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020