我是编程新手。
我正在尝试打印嵌套字典中键的值。
ROOM = ""
ROOM_DESC = ""
ROOM_THIS = ""
ROOM_THAT = ""
ROOM_EXM = ""
randdict = {
"a1": {
ROOM: "room name",
ROOM_DESC: "room desc",
ROOM_THIS: "room this",
ROOM_THAT: "room that",
ROOM_EXM: "room exm",
}
}
print(randdict["a1"][ROOM] + "\n" + randdict["a1"][ROOM_DESC] + "\n" + randdict["a1"][ROOM_THIS])
我期望的结果是:
room name
room desc
room this
相反,我得到的是:
room exm
room exm
room exm
不确定那里出了什么问题,不胜感激。
答案 0 :(得分:1)
将密钥更改为以下内容。
randdict = {
"a1": {
'ROOM' : "room name",
'ROOM_DESC' : "room desc",
'ROOM_THIS': "room this",
'ROOM_THAT': "room that",
'ROOM_EXM': "room exm",
}
}
print(f"{randdict['a1']['ROOM']} \n{randdict['a1']['ROOM_DESC']} \n{randdict['a1']['ROOM_THIS']}")
答案 1 :(得分:1)
使用不同的ROOM,ROOM_DESC,ROOM_THIS,ROOM_THAT和ROOM_EXM值。字典必须具有唯一键。
ROOM = "1"
ROOM_DESC = "2"
ROOM_THIS = "3"
ROOM_THAT = "4"
ROOM_EXM = "5"
randdict = {
"a1": {
ROOM: "room name",
ROOM_DESC: "room desc",
ROOM_THIS: "room this",
ROOM_THAT: "room that",
ROOM_EXM: "room exm",
}
}
print(randdict["a1"][ROOM] + "\n" + randdict["a1"][ROOM_DESC] + "\n" + randdict["a1"][ROOM_THIS])
答案 2 :(得分:0)
ROOM,ROOM_DESC,ROOM_THIS,ROOM_THAT和ROOM_EXM均为“”。这将导致字典被覆盖,并且因为最后一个条目是要打印的房间exm(因为它没有被覆盖)。如果将房间变量切换为唯一变量,则应该可以正常工作
答案 3 :(得分:0)
这里的问题是所有变量ROOM_ *都是相同的空字符串。因此,仅使用最后一个键/值ROOM_EXM:“ room exm”来创建字典。
您可以通过打印字典来进行确认。
您应该为变量ROOM_ *分配一些字符串。甚至像这样:
ROOM = "ROOM"
ROOM_DESC = "ROOM_DESC"
ROOM_THIS = "ROOM_THIS"
ROOM_THAT = "ROOM_THAT"
ROOM_EXM = "ROOM_EXM"