0

Is not both are right?

def report():
"""It prints the value of each resource"""

    print(f"resources['water']: {resources['water']}")
    print(f"resources['milk']: {resources['milk']}")
    print(f"resources['coffee']: {resources['coffee']}")
    print(f"resources['money']: {resources['money']}")
 

             vs

    print(f"resources{['water']}")
    print(f"resources{['milk']}")
    print(f"resources{['coffee']}")
    print(f"resources{['money']}")

hi i tried to acess the dictionary values within the function but it isnot working.I questioned GPT & it spit out the first version which miraculously worked but i couldnot figure out why my version didnot work.

Ahmad Ali
  • 1
  • 1
  • 2

1 Answers1

1

It does not work because the syntax of

 print(f"resources{['money']}")

is wrong. ['money'] is an array of a single value, not a reference to the dictionary. You should put {} around the whole variable.

Let me break it down:

some_variable = 1
f"sometext {some_variable}" # should print "sometext 1

now the same with dict values:

some_variable = resources['water']
f"sometext {some_variable}"

now injecting your dict value directly into the string:

f"sometext {resources['water']}"
Eriks Klotins
  • 4,042
  • 1
  • 12
  • 26
  • Thank you for clarifying,(this is what happens when you don't take a break for too long:)). it should have been like this: print(f"{resources['water']}") – Ahmad Ali Aug 02 '23 at 06:05