Home > Back-end >  How to make a dictionary create new keys and values and not overwrite them?
How to make a dictionary create new keys and values and not overwrite them?

Time:12-04

I'm trying to make a death counter for a small project and make the JSON file look like this

{
    "boss_name": {
        "1": "Then have the time here"
        "2": "same here"
        "3": "ect"
        "4"
        "5"
    }
}

But every time i have tried it overwrites like this:

{
    "boss_name": {
        "5": "03: 12: 2021: 19_59"
    }
}

Here is the full code. I have thought of everything and I can't find any solution. I feel like its something really easy, but really can't think of it.

while True:

    boss_name = input("Are you fighting the boss from last time?"
                      "or is this a new boss?\n"
                      "(type new name to start new boss:"
                      "or type 'n' to use latest boss) ")
    boss_name = boss_name.lower()

    if boss_name == 'n':
        boss_names = []
        try:
            for keys in deaths.keys():
                boss_names.append(keys)
            newy_boss = boss_names.pop()
            boss_name = newy_boss
        except IndexError:
            print("No boss name there, please enter boss name to use")
            boss_name = input("")
            boss_name = boss_name.lower()
    break

def counter(boss):
    death_count.append('1')
    deaths[boss] = {str(len(death_count)): time.strftime('%d: %m: %Y:
    %H_%M')}
    print(f"You have died {str(len(death_count))} times")

CodePudding user response:

You have a dictionary of dictionaries here, and it looks like you're overwriting the inner dictionary every time you record a new death with this line:

deaths[boss] = {str(len(death_count)): time.strftime('%d: %m: %Y: %H_%M')}

I think you want to create a new key, value pair in the dictionary deaths[boss], so try something like this:

deaths[boss][str(len(death_count))] = time.strftime('%d: %m: %Y: %H_%M')
  • Related