0
votes

Need to perform an operation in a dictionary which has a values as a list of dictionaries

my_dicts = \
       {"A": [
             { 'key1 a' : 'value1',
               'key2 a' : 'value2' 
             },

             { 'key1 a' : 'value3',  
               'key2 a' : 'value4' 
             }
            ],

        "B": [
             { 'key1 b' : 'value5',
               'key2 b' : 'value6' 
             },

             { 'key1 b' : 'value7',  
               'key2 b' : 'value8' 
             }
            ]
}

How can we peform an operaion on all the values who have "key2" as substring in its key? i.e. operation on value2, value4, value6 and value8. "key2" is a substring of "key2 a", "key2 b"

1

1 Answers

4
votes

You'll have to loop over all keys of all nested dictionaries:

# generator expression over all values for keys that contain `key2`.
key2values = (v for lst in my_dicts.itervalues() 
                    for dct in lst
                        for k, v in dct.iteritems()
                            if 'key2' in k)

for value in key2values:
    # loops over `value2`, `value4`, `value6`, `value8` in an arbitrary order.

Demonstration:

>>> key2values = (v for lst in my_dicts.itervalues() 
...                     for dct in lst
...                         for k, v in dct.iteritems()
...                             if 'key2' in k)
>>> for value in key2values:
...     print value
... 
value2
value4
value6
value8

If you want to avoid looping over everything, you'll need to rethink your data structure, or build and maintain an index into the structure.

If you needed to manipulate the key-value pair, you need to have more information. You can include the 'parent' dictionary in the loop:

key2values = (dct, k, v for lst in my_dicts.itervalues() 
                    for dct in lst
                        for k, v in dct.iteritems()
                            if 'key2' in k)

and unpack that information when looping over the generator:

for parent, key, value in key2values:
    # parent[key] is equal to value.