0

I couldn't find an answer for this, so can you give a beginner pythonist some help. I have a string and if it is in globals, then I want to use that variable to manipulate it. I get an error that I'm using string to append, when my global variable is a list.

color = []
keyword = "color"
if keyword in globals():
    keyword.append("testing")
mike-gallego
  • 706
  • 2
  • 12
  • 27

1 Answers1

3

globals() returns a dictionary, which you can use like any other dictionary

globals()[keyword] = <my_new_value>
blue_note
  • 27,712
  • 9
  • 72
  • 90
  • Thank you :). And what if I wanted to append a value from the list? globals()[keyword].append("testing") @blue_note – mike-gallego Oct 28 '17 at 14:52
  • 1
    @user3152311: If you *know* that the `globals()[keyword]` is already a list, then `globals()[keyword].append("testing")` should work. – blue_note Oct 28 '17 at 14:58