【发布时间】: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