【问题标题】:Comparing values in dictionary in Python 3 not working?在 Python 3 中比较字典中的值不起作用?
【发布时间】:2020-12-07 07:47:11
【问题描述】:

我一直在努力弄清楚如何在我的 Python 课程中访问(和比较)字典中的值以进行作业。

我认为我对键和值的理解已经足够好,但出于某种原因,无论我尝试什么来比较值,我的程序似乎都不会看到重复的值。

为什么这不起作用?

  if new_value in b_dict.values():
    print("Password already exists...\n")
  else:
    add_to_dict(b_dict, new_key, new_value)
    print("\nPassword added successfully.\n")

完整程序:

def add_to_dict(dict, key, value):
  if key in dict:
    dict[key].append(value)
  else:
    dict[key] = [value]

if __name__ == "__main__":
  b_dict = {"att": ["12345"]}

  new_key = input("Please enter an organization ID to add: ")

  if new_key in b_dict:
    print("Organization exists, adding to this organization...")
  if new_key not in b_dict:
    print("Organization does not exist, adding it...")

  new_value = input("Please input a password: ")

  print("Adding password...")
  if new_value in b_dict.values():
    print("Password already exists...\n")
  else:
    add_to_dict(b_dict, new_key, new_value)
    print("\nPassword added successfully.\n")

  print(b_dict)

我希望当用户输入 att,然后输入 12345 时,程序会通知他们密码已经存在,然后打印原始字典。相反,它总是使用重复的 12345 值打印字典。

【问题讨论】:

    标签: python-3.x dictionary key key-value


    【解决方案1】:

    b_dict.values() 将包含 b_dict 的所有键的所有值 - 这意味着它将包含 ['12345'] 但不包含 '12345' - 我认为您需要检查的是

    if [new_value] in b_dict.values()

    但这适用于这种特殊情况,并且当您附加新值时,您可能需要分别循环遍历所有键或展平值

    【讨论】:

      【解决方案2】:

      这段代码能解决你的问题吗?

        if key in dict:
          dict[key].append(value)
        else:
          dict[key] = [value]
      
      def check_values(value,key) :
          if key in b_dict :
              return value in b_dict[key]
          else : 
              return False
      if __name__ == "__main__":
        b_dict = {"att": ["12345"]}
      
        new_key = input("Please enter an organization ID to add: ")
      
      
        new_value = input("Please input a password: ")
      
        
        
        if check_values(new_value,new_key) == True :
      
            print("They already exist..")
        elif check_values(new_value,new_key) == False :
              print("They are not exits.. adding it")
              if new_key in b_dict :
      
      
                  print("this Organization's password already exist")
      
              else :
                  print("adding new organization and password")
                  add_to_dict(b_dict, new_key, new_value)
      
        
      print(b_dict)    
      

      【讨论】:

      • 这方面不仅仅是获取代码,还包括理解它。请解释你的代码,告诉问这个问题的人做错了什么。为什么?如何解决?
      猜你喜欢
      • 2014-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-04
      • 1970-01-01
      • 2021-03-12
      • 2010-09-30
      • 1970-01-01
      相关资源
      最近更新 更多