Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
comparison
#1
Giving the example below I know I can use a for loop to reach the name but, was wondering if there is a way to reach it in a one liner? Obviously the if name.lower() in data[_class] does not work. I do not know how to iterate over the dicts in the data[_class] part. Any help would be great.

jsonfile:
{
    "wizard": [
        {
            "name": "tabol",
            "age": 23,
            "skills": {
                "fireball": 20,
                "meteor": 15
            }
        },
        {
            "name": "zac",
            "age": 25,
            "skills": {
                "fireball": 10,
                "meteor": 5
            }
        }
    ],
    "cleric": [],
    "warrior": []
}
python snippet
def create_character(file, _class, name, age, skills={}):
    character = {
    'name': name,
    'age': age,
    'skills': skills
    }

    with open(file, 'r+') as json_file:
        data = json.load(json_file)
        print(data[_class])
        if name.lower() in data[_class]:
            print('Alreay here')

create_character(file, 'wizard', 'zac', 25, {'fireball':10, 'meteor': 5})
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#2
This seems to work. I was worried about having to create the data inside a loop. If that makes sense.

def create_character(file, _class, name, age, skills={}):
    character = {
    'name': name,
    'age': age,
    'skills': skills
    }

    with open(file, 'r+') as json_file:
        data = json.load(json_file)
        add_character = True
        for stuff in data[_class]:
            if name.lower() in stuff.values():
                print('That name is already in the database.')
                add_character = False

        if add_character:
            data[_class].append(character)
            json_file.seek(0)
            json.dump(data, json_file, indent=4)
            print('Character created.')

create_character(file, 'wizard', 'tony', 25, {'fireball':10, 'meteor': 5})
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#3
I'm starting to see the value in itertools.chain(). Here it is used to put all characters in one list. Once you have that it is easy to collect all the character names.
import json
from itertools import chain

cdata = json.loads("""
{
    "wizard": [
        {
            "name": "tabol",
            "age": 23,
            "skills": {
                "fireball": 20,
                "meteor": 15
            }
        },
        {
            "name": "zac",
            "age": 25,
            "skills": {
                "fireball": 10,
                "meteor": 5
            }
        }
    ],
    "cleric": [],
    "warrior": []
}""")

print("Zac".lower() in [c.get("name") for c in chain(*cdata.values())])
Are you sure you want to organize your character information this way? I would use the character name as the dictionary key and make the character class a field in the dictionary for the character.
    "tobol": 
        {
            "class": "wizard",
            "age": 23,
            "skills": {
                "fireball": 20,
                "meteor": 15
            }
        },
Reply
#4
Thanks deanhystad. I will use the itertools.chain() when I rewite the code.
I tend to rewrite code several times when doing a practice project.
Also thanks for the input on the json dict structure. I actually thought about doing it that way first. I still
may in one of the rewites.
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply


Forum Jump:

User Panel Messages

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