Filtering dictionaries and creating sub-dictionaries based on keys / values ​​in Python?

Ok, I'm stuck, I need help here ...

If I have a main dictionary, for example:

data = [ {"key1": "value1", "key2": "value2", "key1": "value3"},  
{"key1": "value4", "key2": "value5", "key1": "value6"}, 
{"key1": "value1", "key2": "value8", "key1": "value9"} ]

Now I need to go through this dictionary to format some data, for example:

for datadict in data:  
    for key, value in datadict.items():  
    ...filter the data...

Now, as if I were in the same cycle somehow (if possible ... if not, suggest alternatives, please) check the values ​​of certain keys, and if these values ​​correspond to my presets, I would add that the whole list in another dictionary, thereby effectively creating smaller dictionaries when I exit this main dictionary based on certain keys and values?

, , - , key1 "value1", - :

subdata = [ {"key1": "value1", "key2": "value2", "key1": "value3"},  
{"key1": "value1", "key2": "value8", "key1": "value9"} ]
+5
5

. , , list(). .

- , /, . . k/v- , .

def filter_data(data, predicate=lambda k, v: True):
    for d in data:
         for k, v in d.items():
               if predicate(k, v):
                    yield d


test_data = [{"key1":"value1", "key2":"value2"}, {"key1":"blabla"}, {"key1":"value1", "eh":"uh"}]
list(filter_data(test_data, lambda k, v: k == "key1" and v == "value1"))
# [{'key2': 'value2', 'key1': 'value1'}, {'key1': 'value1', 'eh': 'uh'}]
+9

- , ( dict ..), :

def select_sublist(list_of_dicts, **kwargs):
    return [d for d in list_of_dicts 
            if all(d.get(k)==kwargs[k] for k in kwargs)]

subdata = select_sublist(data, key1='value1')
+3

, , , . :

result = []
for datadict in data:
    for key, value in datadict.items():
        thefiltering()

    if datadict.get('matchkey') == 'matchvalue':
        result.append(datadict)

, " " , . .

+1

Skurmedal, . "" . , - , (, ) , .

def filter_dict(the_dict, predicate=lambda k, v: True):
    for k, v in the_dict.iteritems():
        if isinstance(v, dict) and _filter_dict_sub(predicate, v):
            yield k, v

def _filter_dict_sub(predicate, the_dict):
    for k, v in the_dict.iteritems():
        if isinstance(v, dict) and filter_dict_sub(predicate, v):
            return True
        if predicate(k, v):
            return True
    return False

, dict(filter_dict(the_dict)), .

0

, - :

{ k: v for k, v in <SOURCE_DICTIONARY>.iteritems() if <CONDITION> }

:

src_dict = { 1: 'a', 2: 'b', 3: 'c', 4: 'd' }
predicate = lambda k, v: k % 2 == 0
filtered_dict = { k: v for k, v in src_dict.iteritems() if predicate(k, v) }

print "Source dictionary:", src_dict
print "Filtered dictionary:", filtered_dict

:

Source dictionary: {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
Filtered dictionary: {2: 'b', 4: 'd'}
0

All Articles