简体   繁体   中英

How to access individual items in a nested dictionary that contains another dictionary and a list, and print the items?

I have a dictionary created that looks like the following:

DictItems = {
             'Rule1' : {1 : [S1, S2, S3], 2 : [S4, S5], 3: [S8]},
             'Rule2' : {1 : [S2, S3], 2 : [S2, S4, S5]}
            }

I tried the following:

for key, value, listval in DictItems.items():
   print key, value, listval

But it showed the error: " ValueError: need more than 2 values to unpack ".

How can I access the individual items to print of Manipulate them

Individual items means: I want to check associative rules. So I want to access individual items such as 'Rule1' in an if condition and then check for the values in the next dictionary such as 1 or 2, and the list items.

I think you are overcomplicating this.

Given this dict:

>>> DictItems = {
...              'Rule1' : {1 : ['S1', 'S2', 'S3'], 2 : ['S4', 'S5'], 3: ['S8']},
...              'Rule2' : {1 : ['S2', 'S3'], 2 : ['S2', 'S4', 'S5']}
...             }

You access individual elements using either a key (for a dict) or index (for a sequence) in one or more sets of brackets (paired brackets: [] are AKA subscriptions or __getitem__ operator ):

>>> DictItems['Rule1']
{1: ['S1', 'S2', 'S3'], 2: ['S4', 'S5'], 3: ['S8']}
>>> DictItems['Rule1'][1]
['S1', 'S2', 'S3']
>>> DictItems['Rule1'][1][-1]
'S3'
>>> DictItems['Rule1'][1][-1][0]
'S'

Dissecting the last one there:

 DictItems['Rule1'][1][-1][0]
             ^^^                   key to the top dict
                    ^              key to dict with int key
                       ^^          relative index to a sequence -- last one
                           ^       absolute index to a sequence -- first item

To print then:

>>> for k, li in DictItems['Rule1'].items():
...    print k, li
... 
1 ['S1', 'S2', 'S3']
2 ['S4', 'S5']
3 ['S8']

To access and compare for example:

>>> DictItems['Rule1'][1][2]==DictItems['Rule2'][1][-1]
True

If you want to unpack the example, use nested loops:

>>> for k in DictItems:
...    for sk, li in DictItems[k].items():
...       print k, sk, li
... 
Rule2 1 ['S2', 'S3']
Rule2 2 ['S2', 'S4', 'S5']
Rule1 1 ['S1', 'S2', 'S3']
Rule1 2 ['S4', 'S5']
Rule1 3 ['S8']

Since dicts are unordered, the items will not necessarily come out in a sorted in as-inserted order. You can sort the keys:

>>> for k in sorted(DictItems):
...    for sk in sorted(DictItems[k]):
...       print k, sk, DictItems[k][sk]
... 
Rule1 1 ['S1', 'S2', 'S3']
Rule1 2 ['S4', 'S5']
Rule1 3 ['S8']
Rule2 1 ['S2', 'S3']
Rule2 2 ['S2', 'S4', 'S5'] 

You can also use json for pretty printing a nested dict:

>>> import json
>>> print json.dumps(DictItems, sort_keys=True, indent=4)
{
    "Rule1": {
        "1": [
            "S1", 
            "S2", 
            "S3"
        ], 
        "2": [
            "S4", 
            "S5"
        ], 
        "3": [
            "S8"
        ]
    }, 
    "Rule2": {
        "1": [
            "S2", 
            "S3"
        ], 
        "2": [
            "S2", 
            "S4", 
            "S5"
        ]
    }
}

dict.items() gives you the (key, value) pairs, and will not further unpack the contained dictionaries.

You can only unpack the key and value, where the value is another dictionary object here. To get to the nested dictionary, iterate over that too, perhaps:

for rule, rule_mapping in DictItems.items():
    print rule
    for rulemap_number, listvalue in rule_mapping.items():
        print '{}: {}'.format(rulemap_number, listvalue)

To answer your question, you could nest another loop within the original loop, like so:

for key, value in DictItems.items():
   print key
   for key2, value2 in value.items():
       print key2, value2

And so forth, down as many levels as you want. If you want to get fancy, you can get all recursive up in there but for two levels that will suffice.

NB. Disregard the non-existent naming convention I'm using :P

for rule_num, group in DictItems.items():
    print rule_num
    for index, lst in group.items():
        print "    %s: %s" % (index, lst)

...

Rule2
    1: ['S2', 'S3']
    2: ['S2', 'S4', 'S5']
Rule1
    1: ['S1', 'S2', 'S3']
    2: ['S4', 'S5']
    3: ['S8']

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