How can I extract all values from a dictionary in Python?

前端 未结 11 1972
难免孤独
难免孤独 2020-11-30 17:56

I have a dictionary d = {1:-0.3246, 2:-0.9185, 3:-3985, ...}.

How do I extract all of the values of d into a list l?

11条回答
  •  無奈伤痛
    2020-11-30 18:40

    For nested dicts, lists of dicts, and dicts of listed dicts, ... you can use

    def get_all_values(d):
        if isinstance(d, dict):
            for v in d.values():
                yield from get_all_values(v)
        elif isinstance(d, list):
            for v in d:
                yield from get_all_values(v)
        else:
            yield d 
    

    An example:

    d = {'a': 1, 'b': {'c': 2, 'd': [3, 4]}, 'e': [{'f': 5}, {'g': 6}]}
    
    list(get_all_values(d)) # returns [1, 2, 3, 4, 5, 6]
    

    PS: I love yield. ;-)

提交回复
热议问题