如何从Python中的字典中提取所有值?

Nav*_* C. 161 python dictionary extract

我有一本字典d = {1:-0.3246, 2:-0.9185, 3:-3985, ...}.

如何将所有值提取d到列表中l

Pie*_*don 306

如果你只需要字典的键1,23使用:your_dict.keys().

如果你只需要在字典中的值-0.3246,-0.9185-3985使用:your_dict.values().

如果你想要键和值都使用:your_dict.items()返回一个元组列表[(key1, value1), (key2, value2), ...].

  • 如果您使用的是Python 3,则需要使用`list(your_dict.values())`来获取列表(而不是dict_values对象). (55认同)
  • +1用于同时回答明显的后续问题. (16认同)

zee*_*kay 36

使用 values()

>>> d = {1:-0.3246, 2:-0.9185, 3:-3985}

>>> d.values()
<<< [-0.3246, -0.9185, -3985]
Run Code Online (Sandbox Code Playgroud)

  • list(d.values())给出您显示的输出 (2认同)

Fre*_*die 26

对于 Python 3,您需要:

list_of_dict_values = list(dict_name.values())
Run Code Online (Sandbox Code Playgroud)

  • 感谢您提到需要“list()”方法 (4认同)

Tyl*_*ton 13

如果您想要所有值,请使用:

dict_name_goes_here.values()
Run Code Online (Sandbox Code Playgroud)

如果您想要所有密钥,请使用:

dict_name_goes_here.keys()
Run Code Online (Sandbox Code Playgroud)

如果你想要所有项目(包括键和值),我会使用这个:

dict_name_goes_here.items()
Run Code Online (Sandbox Code Playgroud)


Mic*_*ner 12

对于嵌套的 dicts、dicts 列表和列出的 dicts 的 dicts,...你可以使用

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 
Run Code Online (Sandbox Code Playgroud)

一个例子:

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]
Run Code Online (Sandbox Code Playgroud)

PS:我爱yield。;-)


Dav*_*nan 11

values()在dict上调用方法.


Cha*_*oky 8

我知道这个问题几年前就被问过,但即使在今天也很重要。

>>> d = {1:-0.3246, 2:-0.9185, 3:-3985}
>>> l = list(d.values())
>>> l
[-0.3246, -0.9185, -3985]
Run Code Online (Sandbox Code Playgroud)


小智 5

如果需要所有值,请使用以下命令:

dict_name_goes_here.values()
Run Code Online (Sandbox Code Playgroud)


小智 5

Code of python file containing dictionary

dict={"Car":"Lamborghini","Mobile":"iPhone"}
print(dict)
Run Code Online (Sandbox Code Playgroud)

If you want to print only values (instead of key) then you can use :

dict={"Car":"Lamborghini","Mobile":"iPhone"}
for thevalue in dict.values():
    print(thevalue)
Run Code Online (Sandbox Code Playgroud)

This will print only values instead of key from dictionary

Bonus : If there is a dictionary in which values are stored in list and if you want to print values only on new line , then you can use :

dict={"Car":["Lamborghini","BMW","Mercedes"],"Mobile":["Iphone","OnePlus","Samsung"]}
nd = [value[i] for value in dict.values()
         for i in range(2)]
print(*nd,sep="\n")
Run Code Online (Sandbox Code Playgroud)

参考 - Narendra Dwivedi - 仅从字典中提取值