我有一个字典d ={1:-0.3246, 2:-0.9185, 3:-3985,…}。
我如何将d的所有值提取到列表l中?
我有一个字典d ={1:-0.3246, 2:-0.9185, 3:-3985,…}。
我如何将d的所有值提取到列表l中?
当前回答
dictionary_name={key1:value1,key2:value2,key3:value3}
dictionary_name.values()
其他回答
对于嵌套字典、字典列表和列出字典的字典,…你可以使用
from typing import Iterable
def get_all_values(d):
if isinstance(d, dict):
for v in d.values():
yield from get_all_values(v)
elif isinstance(d, Iterable) and not isinstance(d, str): # or list, set, ... only
for v in d:
yield from get_all_values(v)
else:
yield d
一个例子:
d = {'a': 1, 'b': {'c': 2, 'd': [3, 4]}, 'e': [{'f': 5}, {'g': set([6, 7])}], 'f': 'string'}
list(get_all_values(d)) # returns [1, 2, 3, 4, 5, 6, 7, 'string']
非常感谢@vicent指出字符串也是可迭代的!我相应地更新了我的答案。
PS:是的,我喜欢屈服。: -)
如果你只需要字典键1、2和3,请使用:your_dict.keys()。
如果你只需要字典值-0.3246、-0.9185和-3985,使用:your_dict.values()。
如果同时需要键和值,请使用:your_dict.items(),它将返回元组列表[(key1, value1), (key2, value2),…]。
正常Dict.values ()
会返回这样的东西
dict_values ([' value1 '])
dict_values ([' value2 '])
如果你只需要值使用
使用这个
list(Dict.values())[0] #在列表下面
dictionary_name={key1:value1,key2:value2,key3:value3}
dictionary_name.values()
对于Python 3,你需要:
list_of_dict_values = list(dict_name.values())