Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
76 views
in Technique[技术] by (71.8m points)

python - Get inner nested dictionary

I am trying to get arbitrary values from nested dictionaries, but getting an error. My approach works for one level dict like this:

    table = [
        {
            "A": 157,
            "B": 221,
            "C": 330,
            "D": 380
        },
        {
            "A": 510,
            "B": 547,
            "C": 660,
            "D": 780
        },
        {
            "A": 791,
            "B": 1111,
            "C": 1200,
            "D": 3000
        },
        ]

    from operator import itemgetter
    val = 525
    for dv in table:
        column_B = max(val, dv['B'])
        if val <= dv['B']:
            column_A = (dv['A'])
            column_C = dv['C']
            pct = dv['D']
            break

But if I nest the dicts, I get an error.

    table = [
        "inner":{
        
            {   "A": 157,
                "B": 221,
                "C": 330,
                "D": 380
            },
            {
                "A": 510,
                "B": 547,
                "C": 660,
                "D": 780
            },
            {
                "A": 791,
                "B": 1111,
                "C": 1200,
                "D": 3000
            },
        }

    ]

I get an error with above nested dict. I tried slicing, even tried reduced function but could not make it work up this point. What am I getting wrong here?

question from:https://stackoverflow.com/questions/65873128/get-inner-nested-dictionary

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

[] denotes a list. {} denotes a dictionary. It looks like you've gotten the two partially mixed up. In order for table to make sense, table should be a dictionary, and "inner" should be a list.

# This has a key, therefore it's a dict.
table = {
    # This has no keys, so it's a list.
    "inner": [
    
        {   "A": 157,
            "B": 221,
            "C": 330,
            "D": 380
        },
        {
            "A": 510,
            "B": 547,
            "C": 660,
            "D": 780
        },
        {
            "A": 791,
            "B": 1111,
            "C": 1200,
            "D": 3000
        },
    ]

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...