简体   繁体   中英

Calling value in n-level nested list in python

I am having an issue with calling 'hello'. In first example, no problem:

d = {'k1':{'k2':'hello'}}

Grab 'hello'

d['k1']['k2']

Output: 'hello'

But the second example, I cannot get my head around nested dictionary in list.

d = {'k1':[{'nest_key':['this is deep',['hello']]}]}

#Grab hello

d['k1'][0]

Output:

{'nest_key': ['this is deep', ['hello']]}

I tried d['k1']['nest_key'] but it gets me error. I tried to look it up in docs but it didn't help.

d[k1] is a list with 1 element which is a dict. so d[k1][0] accesses the 2nd dict. d[k1][0][nest_key] accesses the inner lis which is ["this is deep'',[hallo]]

so d[k1][0][nest_key][1][0] gives you the "hallo"

It is all about the square brackets defining lists within the dict

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