Home > Software design >  Printing a variable from a dictionary gives an error and says it doesn't exist
Printing a variable from a dictionary gives an error and says it doesn't exist

Time:08-16

I'm trying to print a variable that's stored in a dictionary, but when I try to print it, it says:

  File "C:\Users\defomyname\Desktop\thing.py", line 24, in <module>
main()   File "C:\Users\defomyname\Desktop\thing.py", line 20, in main
print(f"Value 1: {settings.value1}") AttributeError: 'dict' object has no attribute 'value1'. >Did you mean: 'values'?

Code:

is_on = None
value1 = None
value2 = None

settings = {
    is_on: False,
    value1: 10,
    value2: 20
}



def main():
    #print(f"Enabled: {settings.is_on}")
    print(f"----------------")
    print(f"Value 1: {settings.value1}")
    print(f"Value 2: {settings.value2}")
    print("-----------------")

main()

CodePudding user response:

You're assigning repetitive identical keys to a dictionary. the dictionnary structure in Python is designed to have only unique and distinct keys. Your code is basically like this:

settings = {
None : False,
None : 10,
None : 20
}

Now, if you print again the settings variable, the None key will only be assigned to 20 because it was the last assignment.

this is the current state of settings:

settings = {None: 20}

Finally, the settings variable is dictionnary. and dictionnaries has only 3 attributes:

  1. keys() : list of the settings keys:
print(settings.keys())
  1. values() : list of its values:
print(settings.values())
  1. items() : list of its items (key, value):
print(settings.items())

output:

dict_keys([None])
dict_values([20])
dict_items([(None, 20)])

the values of a specific key can be obtained by settings[None].

  • Related