Glasgow
Glasgow

Reputation: 94

Looping through a nested dictionary

I have a nested dictionary set up that I'm trying to access but having trouble accessing the 'nextmo' part when the key is set to something my user decides (I've set to Feb in the example below). Ideally it should print 'Mar'

D = {'Jan': {'days': 31, 'nextmo': 'Feb', 'prevmo': 'Dec'},
 'Feb': {'days': 29, 'nextmo': 'Mar', 'prevmo': 'Jan'},
 'Mar': {'days': 31, 'nextmo': 'Apr', 'prevmo': 'Feb'},
 'Apr': {'days': 30, 'nextmo': 'May', 'prevmo': 'Mar'}, 
 'May': {'days': 31, 'nextmo': 'Jun', 'prevmo': 'Apr'},
 'Jun': {'days': 30, 'nextmo': 'Jul', 'prevmo': 'May'},
 'Jul': {'days': 31, 'nextmo': 'Aug', 'prevmo': 'Jun'},
 'Aug': {'days': 31, 'nextmo': 'Sep', 'prevmo': 'Jul'}, 
 'Sep': {'days': 30, 'nextmo': 'Oct', 'prevmo': 'Aug'},
 'Oct': {'days': 31, 'nextmo': 'Nov', 'prevmo': 'Sep'},
 'Nov': {'days': 30, 'nextmo': 'Dec', 'prevmo': 'Nov'},
 'Dec': {'days': 31, 'nextmo': 'Jan', 'prevmo': 'Jan'},}

bday_month_in = "Feb"

for k, v in D.items():
    if bday_month_in is dict:
       print(bday_month_in['nextmo'])

Upvotes: 1

Views: 64

Answers (2)

little-dude
little-dude

Reputation: 1674

First, there is one major issue in your code:

if bday_month_in is dict:
    # [...]

Here, bday_month_in is a string ("Feb"), not a dictionary, so this if statement will never be true.

Now if you want to iterate over nested dictionnaries you can do that:

for (month, inner_dict) in D.items():                   
    print("Month: {}".format(month))
    for (key, value) in inner_dict.items():
        print("   key={}, value={}".format(key, value))

But it seems from your question that you don't even need to iterate over nested dictionnaries:

D['Feb']['nextmo']

Upvotes: 1

jpp
jpp

Reputation: 164623

If you just want the next month after bda_month_in, then this should work:

bday_month_in = 'Feb'
D[bday_month_in]['nextmo']  # 'Mar'

Upvotes: 4

Related Questions