在Python 3中比较字典中的值不起作用?

操作系统

我一直在努力寻找如何访问(比较)字典中的值以进行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值的字典。

莫尔兹

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

if [new_value] in b_dict.values()

但这在特定情况下会起作用,并且当您添加新值时,您可能需要分别循环遍历所有键或展平值

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章