NRD
NRD

Reputation: 141

accessing nested dict fails

I have a nested dict which I construct over a period of several processes. To construct the dict I pass it to some functions, populate it and return it. With just a single entry the dict is constructed as such:

{K: { K:V, K:V } }

For a near real world example:

mydict = {"www.google.com": {"date":"1/1/19","text":"moo"},
          "www.yahoo.com": {"date":"1/2/19","text":"woof"}}

If I print(mydict) I see exactly as I would expect. However when I attempt to iterate through the dict I am unable to get the values from my nested dict by using the following:

for k,v in mydict.items():
    print(mydict[k][text])

I instead get the error:

NameError: name 'text' is not defined

But then when I perform the following it works:

for k,v in mydict.items():
    print(mydict[k])

I am presented with results such as:

{"date":"1/1/19","text":"moo"}

{"date":"1/2/19","text":"woof"}

What am I doing wrong?

Upvotes: 1

Views: 57

Answers (3)

Bendang
Bendang

Reputation: 321

You missed the " double quotes in your text : Here is the correct one

for k,v in mydict.items():
    print(mydict[k]["text"])

Upvotes: 1

codrelphi
codrelphi

Reputation: 1065

You have to use "text" instead of text.

mydict = {"www.google.com":{"date":"1/1/19","text":"moo"},
      "www.yahoo.com":{"date":"1/2/19","text":"woof"}}

for k,v in mydict.items():
    print(mydict[k]["text"])

Output

moo
woof

Upvotes: 1

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

You need to quote te "text" otherwise it's taken as variable name

print(mydict[k]['text'])

Upvotes: 2

Related Questions