简体   繁体   中英

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

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'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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