#πŸ”’ Creating dictionaries in code creates a defaultdict instead

15 messages Β· Page 1 of 1 (latest)

tacit cradle
#

I'm making a "game engine" for a game that's supposed to be played entirely within the python shell, and I got to the part where I am making the system responsible for handling story flags and the general progress of the player.

Problem is though, whenever I create a normal dictionary in python, it appears to be a default dict instead.

Here is a python file that represents this problem in the clearest way:

import json

BRANCH_LIST = ["storybranch1", 'storybranch2', 'storybranch3']

NPC_VALUES = {
    "NPC1": {
        "Likeness": 0,
        "Hate": 0,
        "Trust": 0,
        "Respect": 0
    },
    "NPC2": {
        "Likeness": 0,
        "Hate": 0,
        "Trust": 0,
        "Respect": 0
    }
}

FLAGS = {
    "flagA": True,
    "flagB": False,
    "flagC": True
}

QUEST_FLAGS = {
    "quests_completed": 0,
    "side-quests_completed": 0,
    
    "quest_list": ["quest1", "quest2", "quest3"], 
    
    "individual_completion": {
        "quest1_completed": False,
        "quest2_completed": False
    }
}

def change_flag(flag_name: str, value):
    FLAGS[flag_name] = value


change_flag("asdw", True)
print(FLAGS.keys(), FLAGS.values())

The output of this program looks like this:
dict_keys(['flagA', 'flagB', 'flagC', 'asdw']) dict_values([True, False, True, True])

While the expected output is something like this:
KeyError: 'asdw'

I am working on a Linux Mint 22.2 machine with python 3.12.3
There is no virutal environment present in my project.

Any ideas why this is happening?

keen groveBOT
#

@tacit cradle

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

remote crescent
#

this isn't a key error, because you are making a new key

olive basin
#

you can't make a defaultdict accidentally

remote crescent
#

my_dict[key] = value makes a new key

tacit cradle
remote crescent
#

sure. but what you really want here is a type with a fixed set of keys, like a dataclass

tacit cradle
remote crescent
#

defaultdicts add a key when you try to access a key that doesn't exist

#

setting a key just sets the key

tacit cradle
#

okay yeah that makes a ton of sense

tacit cradle
#

!close

keen groveBOT
#
Python help channel closed with !close

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.