所以我在一个带有多个键的dict()中使用了一个dict()。其中一个键是ID号。我正在尝试反向查找以使用与具有该ID的相应用户匹配的ID并返回用户。但我还没弄明白怎么做。我在想这个:
users = {"jim": {"id": 1, "rank": [1, "chaz", 12], "points": 233}, "bill": {"id": 14, "rank": [2, "franklin", 14], "points": 455}}
def reverse_lookup(id_num, d=users):
try:
id_num = id_num.replace("#", "")
for user in d:
if d[user]["id"] == id_num:
return user
except Exception as e: return "Error: %s" % e
print(reverse_lookup("#14"))
returns None
此代码是否正确且功能正常?因为我真的怀疑它会起作用。
答案 0 :(得分:1)
拿这个并与你的比较:
def reverse_id_lookup(id_code, users):
id_code = int(id_code.split("#", 1)[1])
for user, info in users.items():
if info['id'] == id_code:
return user
else:
raise Exception("ID does not exist yet.")