Revision 1716a15d kamaki/cli/utils/__init__.py

b/kamaki/cli/utils/__init__.py
31 31
# interpreted as representing official policies, either expressed
32 32
# or implied, of GRNET S.A.
33 33

  
34
from sys import stdout, stdin
34
from sys import stdout
35 35
from re import compile as regex_compile
36 36
from time import sleep
37 37
from os import walk, path
......
458 458
    for item in list_of_dicts:
459 459
        assert isinstance(item, dict), 'Item %s not a dict' % item
460 460
        item.pop(key_to_remove, None)
461

  
462

  
463
def filter_dicts_by_dict(
464
    list_of_dicts, filters,
465
    exact_match=True, case_sensitive=False):
466
    """
467
    :param list_of_dicts: (list) each dict contains "raw" key-value pairs
468

  
469
    :param filters: (dict) filters in key-value form
470

  
471
    :param exact_match: (bool) if false, check if the filter value is part of
472
        the actual value
473

  
474
    :param case_sensitive: (bool) revers to values only (not keys)
475

  
476
    :returns: (list) only the dicts that match all filters
477
    """
478
    new_dicts = []
479
    for d in list_of_dicts:
480
        if set(filters).difference(d):
481
            continue
482
        match = True
483
        for k, v in filters.items():
484
            dv, v = ('%s' % d[k]), ('%s' % v)
485
            if not case_sensitive:
486
                dv, v = dv.lower(), v.lower()
487
            if not ((
488
                    exact_match and v == dv) or (
489
                    (not exact_match) and v in dv)):
490
                match = False
491
                break
492
        if match:
493
            new_dicts.append(d)
494
    return new_dicts

Also available in: Unified diff