为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

互换的青春 2022-04-23 16:53:05
我有一本包含唯一 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、姓名和生日。有没有办法将这些键转换为变量,并给出相同的输出?
查看完整描述

3 回答

?
开满天机

TA贡献1786条经验 获得超13个赞

你可以简单地使用一个列表来达到这个目的


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: 1

Full Name: JM Cruz

Birthday: October 5, 1980

----------------------

ID: 2

Full Name: JD Castillo

Birthday: August 18, 1979

----------------------

ID: 3

Full Name: Maria Torres

Birthday: August 3, 1992

----------------------


查看完整回答
反对 回复 2022-04-23
?
jeck猫

TA贡献1909条经验 获得超7个赞

您只能创建一个dict,并且密钥是用户 ID。其他信息如“fn, ln, dob”可能在列表中。您将按特定顺序附加这 3 个信息,以便您可以从列表中检索任何必要的信息。

样本:

db = {"1" : [fn1, ln1, dob1], "2": [fn2, ln2, dob2]}


查看完整回答
反对 回复 2022-04-23
?
三国纷争

TA贡献1804条经验 获得超7个赞

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)


查看完整回答
反对 回复 2022-04-23
  • 3 回答
  • 0 关注
  • 103 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信