【问题标题】:Using a users input to search dictionary keys and print that keys matching value使用用户输入搜索字典键并打印匹配值的键
【发布时间】:2019-12-12 21:56:20
【问题描述】:

我正在使用 tkinter,因为我已经设置了我的 gui 和条目、标签和按钮。我正在尝试使用用户输入的条目来搜索我的字典键,并打印键入的键的值。例如。

d = {"A":1, "B":2, "C":3}

用户在条目中输入 B 按下按钮,如果 input == "B" 则将 2 打印到标签,否则打印“不匹配”

至少是这样的想法。

我可以查看用户输入是否在字典中,并将一些字符串打印到标签,但不能打印输入到条目中的键的值。

我刚开始用 python 编程并练习。我在这个问题上搜索了大约两天,只能找到基本上跳过 if 语句并直接进入 else 的循环。或者如果条目是“A”,它会打印值 3。我认为这是某种反向字典。所以我试着自己弄清楚。如果我走在正确的轨道上,那就太好了,哈哈,但如果我完全错了..

所以我尝试了普通的 if else 语句、for 循环和使用字典的方法。

d = {"AA":1, "BB":2, "CC":3}

  def btn_Clicked():
    x = txt.get()
    if x in d.keys():
        decision.configure(text = "Your value, " + "this is where I'm lost, I'd like it to print the value of that specific key)
    else:
        decision.configure(text = "No key found")


btn = ttk.Button(win, text = "Find value", command = btn_clicked)
btn.grid(column = 2, row = 0)


txt = ttk.Entry(win, width = 10)
txt.grid(column = 1, row = 0)

position_entry = ttk.Label(win, text= "Enter Key", font = ("Arial Bold", 12))
position_entry.grid(column= 0, row = 0 )

decision = ttk.Label(win, text = "", font = ("Arial Bold", 10))
decision.grid(column= 0,row = 1)

我也尝试过类似

 if txt.get() == list(d.keys())[0]:
          decision.configure(text = "Your Value is " + str(list(d.values())[0])

在该示例中,我得到了相应的值,但它仅适用于我输入的输入,[0]、[1] 等字典中的项目。

没有错误消息,只是没有做我想做的事。 如果 entry == 到字典中的键,则将“消息”+该键值打印到标签。

【问题讨论】:

  • 你能输入你的实际代码吗? hand 未在任何地方声明。它应该是dict 吗? (顺便说一句,最好不要使用dict之类的关键字作为变量名)..
  • 我很抱歉。 d 是字典变量。并且 hand.keys() 应该替换为 d.keys()

标签: python dictionary for-loop if-statement methods


【解决方案1】:

由于是字典,所以可以直接使用get()来获取key的值。

def btn_Clicked():
    x = txt.get()
    check_in_dict = dict.get(x)

    if check_in_dict:
        decision.configure(text = "Your value, " + str(check_in_dict))
    else:
        decision.configure(text = "No key found")

【讨论】:

  • 如果键不在字典上,这将引发异常。考虑改用dict.get(x),因为__getitem__(key) 只是dict[key]的不同方式
  • 同意d.get(x)如果找不到会返回None,所以可以在后面的if语句中查看结果,如果没有值则返回“No key found”错误错误.
  • 是的,我同意你的看法。我已经更改了上面的代码。
  • 效果很好,非常感谢。就像我说的一般编码/堆栈溢出的新手。很棒的体验,感谢大家的意见。
【解决方案2】:

使用get 方法,如果找不到密钥,则返回None

v = d.get(x)
if x:
    decision.configure(text = f"Your value, {v}")
else:
    decision.configure(text = f"No key found for {x}")

【讨论】:

    【解决方案3】:
    dictionary = {"AA":1, "BB":2, "CC":3}
    

    下面的代码将进入按下的按钮

    key = input("the key") # key is assumed to be input here
    
    try:
        value = dictionary[key] # user entered key
    
        # do what you want with key and its value
        decision.configure(text = "Your value, " + value)
    
    # if key not found in dict it would raise KeyError
    except KeyError:
        # key not found message goes here
        decision.configure(text = "No key found")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-16
      • 2015-05-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多