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

前端 未结 11 1935
难免孤独
难免孤独 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:46
    d = <dict>
    values = d.values()
    
    0 讨论(0)
  • 2020-11-30 18:47

    If you want all of the values, use this:

    dict_name_goes_here.values()
    

    If you want all of the keys, use this:

    dict_name_goes_here.keys()
    

    IF you want all of the items (both keys and values), I would use this:

    dict_name_goes_here.items()
    
    0 讨论(0)
  • 2020-11-30 18:47

    Pythonic duck-typing should in principle determine what an object can do, i.e., its properties and methods. By looking at a dictionary object one may try to guess it has at least one of the following: dict.keys() or dict.values() methods. You should try to use this approach for future work with programming languages whose type checking occurs at runtime, especially those with the duck-typing nature.

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

    If you only need the dictionary keys 1, 2, and 3 use: your_dict.keys().

    If you only need the dictionary values -0.3246, -0.9185, and -3985 use: your_dict.values().

    If you want both keys and values use: your_dict.items() which returns a list of tuples [(key1, value1), (key2, value2), ...].

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

    If you want all of the values, use this:

    dict_name_goes_here.values()
    
    0 讨论(0)
提交回复
热议问题