简体   繁体   中英

How do I access a dictionary value, with a variable for the key, if it is wrapped in eval?

I am using a variable to name a specific dictionary and using the eval() function to do this. The user input is from tkinter.

x6x6 = {"2":r"arrays\2x1_6x6_2up.txt", "4":r"arrays\2x2_6x6_4up.txt", "8":"arrays\2x4_6x6_8up.txt"}

mydict = "x%sx%s" % (numX.get(), numY.get())

numPnls = pnls.get()

If I use the variable numPnls plainly I get TypeError: string indices must be integers:

print(eval(mydict[numPnls]))

If I try to eval it also I get IndexError: string index out of range:

print(eval(mydict[eval(numPnls)]))

This produces the expected results:

print(x6x6[numPnls])

and this prints everything:

print(eval(mydict))

Turns out I had the syntax wrong:

print(eval(mydict)[numPnls])

using user2357112's method of a 2d dictionary though, much easier:

print(outerdict[mydict][numPnls])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM