简体   繁体   English

从嵌套字典中打印出一个值

[英]Printing out a value from a nested dictionary

I am new to programming.我是编程新手。

I'm trying to print out the value of a key within a nested dictionary.我正在尝试打印嵌套字典中键的值。

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

The result I was expecting was:我期待的结果是:

room name
room desc
room this

Instead what I got was:相反,我得到的是:

room exm
room exm
room exm

Not quite sure what went wrong there, an explanation would be appreciated.不太确定那里出了什么问题,将不胜感激。

change your keys to the following.将您的密钥更改为以下内容。

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']}")

Use different values of ROOM, ROOM_DESC, ROOM_THIS, ROOM_THAT and ROOM_EXM.使用 ROOM、ROOM_DESC、ROOM_THIS、ROOM_THAT 和 ROOM_EXM 的不同值。 Dictionaries must have unique keys.字典必须有唯一的键。

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

ROOM, ROOM_DESC, ROOM_THIS, ROOM_THAT and ROOM_EXM are all "". ROOM、ROOM_DESC、ROOM_THIS、ROOM_THAT 和 ROOM_EXM 都是“”。 this causes the dictionary to be overwritten, and because the last entry was room exm that is what gets printed (because it wasn't overwritten).这会导致字典被覆盖,并且因为最后一个条目是 room exm 是被打印的(因为它没有被覆盖)。 If you switch the room variables to be unique it should work如果您将房间变量切换为唯一的,它应该可以工作

The problem here is that all your variables ROOM_* are the same empty string.这里的问题是所有变量 ROOM_* 都是相同的空字符串。 So your dictionary is being created only with the last key/value ROOM_EXM: "room exm".因此,您的字典仅使用最后一个键/值 ROOM_EXM:“room exm”创建。

You can check that by printing your dictionary.您可以通过打印字典来检查。

You should assign some string to your variables ROOM_*.您应该为变量 ROOM_* 分配一些字符串。 Even something like:甚至是这样的:

ROOM = "ROOM"
ROOM_DESC = "ROOM_DESC"
ROOM_THIS = "ROOM_THIS"
ROOM_THAT = "ROOM_THAT"
ROOM_EXM = "ROOM_EXM"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM