有没有一种方法可以通过声明构成其键值对的变量来创建字典?

时间:2019-08-03 13:22:51

标签: python python-3.x key-value dictionary-comprehension

我有一本字典,其中包含唯一的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 个答案:

答案 0 :(得分:0)

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

示例:

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

答案 1 :(得分:0)

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)

答案 2 :(得分:-1)

您可以为此简单地使用列表

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