[英]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.我正在使用一个变量来命名一个特定的字典,并使用 eval() function 来执行此操作。 The user input is from tkinter.
用户输入来自 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:如果我清楚地使用变量 numPnls 我得到 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:如果我尝试评估它,我也会得到 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:不过,使用 user2357112 的二维字典方法要容易得多:
print(outerdict[mydict][numPnls])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.