Skip to main content

Search a List of Dictionaries for a particular value in Python.

def search_list_of_dicts(key, value, list_of_dicts):
    """
    Search a List of Dictionaries for a particular value.

    Example Usage:

        list_of_dicts = [
            {
                'option': 'printWidth',
                'cli': '--print-width',
                'default': '80'
            },
            {
                'option': 'singleQuote',
                'cli': '--single-quote',
                'default': 'false'
            },
            {
                'option': 'trailingComma',
                'cli': '--trailing-comma',
                'default': 'none'
            }
        ]

        #
        # Get the matched dict in the list of dictionaries:
        dict_match = search_list_of_dicts('option', 'singleQuote', list_of_dicts)
        >> [{'default': 'false', 'option': 'singleQuote', 'cli': '--single-quote'}]

        #
        # Get the cli key value from the matched list of dictionaries:
        dict_match2 = search_list_of_dicts('option', 'singleQuote', list_of_dicts)
        print(dict_match2[0]['cli'])
        >> --single-quote

    Hat tip to https://stackoverflow.com/a/24845196

    :param key: The key to search for in the list of dictionaries.
    :param value: The value to search for in the list of dictionaries.
    :param list_of_dicts: The list of dictionaries to search.
    :return: The matching dictionary, or None if not found.
    """
    try:
        return [element for element in list_of_dicts if element[key] == value]
    except KeyError:
        pass
    return None