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

前端 未结 11 1934
难免孤独
难免孤独 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:28
    dictionary_name={key1:value1,key2:value2,key3:value3}
    dictionary_name.values()
    
    0 讨论(0)
  • 2020-11-30 18:29

    Call the values() method on the dict.

    0 讨论(0)
  • 2020-11-30 18:32

    To see the keys:

    for key in d.keys():
        print(key)
    

    To get the values that each key is referencing:

    for key in d.keys():
        print(d[key])
    

    Add to a list:

    for key in d.keys():
        mylist.append(d[key])
    
    0 讨论(0)
  • 2020-11-30 18:40

    Use values()

    >>> d = {1:-0.3246, 2:-0.9185, 3:-3985}
    
    >>> d.values()
    <<< [-0.3246, -0.9185, -3985]
    
    0 讨论(0)
  • 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. ;-)

    0 讨论(0)
  • 2020-11-30 18:41

    For Python 3, you need:

    list_of_dict_values = list(dict_name.values())
    
    0 讨论(0)
提交回复
热议问题