0

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"

4

1 回答 1

4

您必须遍历所有嵌套字典的所有键:

# 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.

示范:

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

如果您想避免循环遍历所有内容,则需要重新考虑数据结构,或者构建并维护结构中的索引。

如果您需要操作键值对,则需要更多信息。您可以在循环中包含“父”字典:

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

并在遍历生成器时解压缩该信息:

for parent, key, value in key2values:
    # parent[key] is equal to value.
于 2013-03-03T13:30:10.597 回答