unscribed
unscribed

Reputation: 3

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.

Upvotes: 0

Views: 55

Answers (4)

rasc42
rasc42

Reputation: 103

The problem here is that all your variables ROOM_* are the same empty string. So your dictionary is being created only with the last key/value ROOM_EXM: "room exm".

You can check that by printing your dictionary.

You should assign some string to your variables ROOM_*. Even something like:

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

Upvotes: 0

Andrey Kachow
Andrey Kachow

Reputation: 1126

Use different values of ROOM, ROOM_DESC, ROOM_THIS, ROOM_THAT and 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])

Upvotes: 1

wmoskal
wmoskal

Reputation: 295

ROOM, ROOM_DESC, ROOM_THIS, ROOM_THAT and ROOM_EXM are all "". 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). If you switch the room variables to be unique it should work

Upvotes: 0

Yatish Kadam
Yatish Kadam

Reputation: 472

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

Upvotes: 1

Related Questions