有没有办法通过声明构成其键值对的变量来创建字典?

我有一本包含唯一 ID、姓名和生日的字典。这本字典就像一个生日数据库,我的挑战是我不知道如何在其中放入多个 ID。


db = {"id": 1, "fn": "JM", "ln" : "Cruz", "dob": "October 5, 1980"}

db1 = {"id": 2, "fn": "JD", "ln" : "Castillo", "dob": "August 18, 1979"}

db2 = {"id": 3, "fn": "Maria", "ln" : "Torres", "dob": "August 3, 1992"}


print("ID: " + str(db["id"]))

print("Full Name: " + db["fn"] + " " + db["ln"])

print("Birthday: " + db["dob"])

print("----------------------")

print("ID: " + str(db1["id"]))

print("Full Name: " + db1["fn"] + " " + db1["ln"])

print("Birthday: " + db1["dob"])

print("----------------------")

print("ID: " + str(db2["id"]))

print("Full Name: " + db2["fn"] + " " + db2["ln"])

print("Birthday: " + db2["dob"])

print("----------------------")

在上面的代码中,您会注意到我必须重复创建字典才能枚举多组 ID、姓名和生日。有没有办法将这些键转换为变量,并给出相同的输出?


互换的青春
浏览 104回答 3
3回答

开满天机

你可以简单地使用一个列表来达到这个目的dblist = []dblist.append( {"id": 1, "fn": "JM", "ln" : "Cruz", "dob": "October 5, 1980"})dblist.append( {"id": 2, "fn": "JD", "ln" : "Castillo", "dob": "August 18, 1979"})dblist.append({"id": 3, "fn": "Maria", "ln" : "Torres", "dob": "August 3, 1992"})for db in dblist:    print("ID: " + str(db["id"]))    print("Full Name: " + db["fn"] + " " + db["ln"])    print("Birthday: " + db["dob"])    print("----------------------")输出ID: 1Full Name: JM CruzBirthday: October 5, 1980----------------------ID: 2Full Name: JD CastilloBirthday: August 18, 1979----------------------ID: 3Full Name: Maria TorresBirthday: August 3, 1992----------------------

jeck猫

您只能创建一个dict,并且密钥是用户 ID。其他信息如“fn, ln, dob”可能在列表中。您将按特定顺序附加这 3 个信息,以便您可以从列表中检索任何必要的信息。样本:db = {"1" : [fn1, ln1, dob1], "2": [fn2, ln2, dob2]}

三国纷争

db = [{"id": 1, "fn": "JM", "ln" : "Cruz", "dob": "October 5, 1980"}, {"id": 2, "fn": "JD", "ln" : "Castillo", "dob": "August 18, 1979"}, {"id": 3, "fn": "Maria", "ln" : "Torres", "dob": "August 3, 1992"}]for i in db:    print(f"ID: {i['id']}\nFull Name: {i['fn']} {i['ln']}\nBirthday: {i['dob']}\n{'-' * 22}")或者你可以“玩”拆包:for i in db:    print("ID: {}\nFull Name: {} {}\nBirthday: {}\n".format(*i.values()) + "-" * 22)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python