简体   繁体   English

如果字典值包含在 eval 中,如何访问带有键变量的字典值?

[英]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.

相关问题 如何在训练/评估期间访问Tensorflow中标签的值? - How do I access the value of a label in Tensorflow during training/eval? 如何将变量分配给 eval / exec 值? - How do i assign a variable to a eval / exec value? 如何访问从 ListView 传递到模板的上下文变量中的字典键? - How do I access a dictionary key in a context variable that gets passed from a ListView to a template? 如果键是一个元组,如何在字典中访问键的值? - How can I access the value of a key in a dictionary if the key is a tuple? 我如何将字典 append 作为现有字典键的另一个值 - How do I append a dictionary as another value to an existing dictionary key 如何在字典中按值访问键? - How to access key by value in a dictionary? 如何访问字典中的项键名称然后找到值? (Python) - How do I access item key names in a dictionary and then find the value? (Python) 如何在字典中找到最接近但不超过变量的值的键? - How do I find the key of a value in a dictionary that closest to, but not more than, a variable? 在Django模板中,当密钥存储在变量中时,如何在字典中打印值? - In a Django template, how do I print the value in a dictionary when the key is stored in a variable? 如何从字典中的字符串中访问字典中的值 - How do I access a value from a dictionary within a dictionary that is a string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM