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

发布于 2024-11-28 21:36:19 字数 123 浏览 2 评论 0原文

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

昇り龍 2024-12-05 21:36:20

您可以使用 items()keys()values() 来获取键和值,或者仅获取键和值分别在字典中,如下所示:

person = {'name':'John', 'age':35, 'gender':'Male'}

print(person.items()) # dict_items([('name', 'John'), ('age', 35)])
print(person.keys()) # dict_keys(['name', 'age'])
print(person.values()) # dict_values(['John', 35])

并且,您可以使用 for 迭代 items()keys()values() 循环如下所示:

person = {'name':'John', 'age':35}

for key, value in person.items(): # name John
    print(key, value)             # age 35
    
for key in person.keys(): # name
    print(key)            # age
    
for value in person.values(): # John
    print(value)              # 35

但是,您无法访问items()keys()values()[] 如下所示,因为存在错误:

person = {'name':'John', 'age':35}

print(person.items()[0]) # Error
print(person.keys()[0]) # Error
print(person.values()[0]) # Error

但是,如果使用 list(),您可以访问它们与 [] 如下所示:

person = {'name':'John', 'age':35}

print(list(person.items())[0]) # ('name', 'John')
print(list(person.keys())[0]) # name
print(list(person.values())[0]) # John

You can use items(), keys() and values() to get both the keys and values, only the keys and only the values in a dictionary respectively as shown below:

person = {'name':'John', 'age':35, 'gender':'Male'}

print(person.items()) # dict_items([('name', 'John'), ('age', 35)])
print(person.keys()) # dict_keys(['name', 'age'])
print(person.values()) # dict_values(['John', 35])

And, you can iterate items(), keys() and values() with for loop as shown below:

person = {'name':'John', 'age':35}

for key, value in person.items(): # name John
    print(key, value)             # age 35
    
for key in person.keys(): # name
    print(key)            # age
    
for value in person.values(): # John
    print(value)              # 35

But, you cannot access items(), keys() and values() with [] as shown below because there are errors:

person = {'name':'John', 'age':35}

print(person.items()[0]) # Error
print(person.keys()[0]) # Error
print(person.values()[0]) # Error

But, if using list(), you can access them with [] as shown below:

person = {'name':'John', 'age':35}

print(list(person.items())[0]) # ('name', 'John')
print(list(person.keys())[0]) # name
print(list(person.values())[0]) # John
oО清风挽发oО 2024-12-05 21:36:20

Pythonic 鸭子类型原则上应该确定对象可以做什么,即它的属性和方法。通过查看字典对象,人们可能会尝试猜测它至少具有以下一种: dict.keys() 或 dict.values() 方法。您应该尝试使用这种方法来处理在运行时进行类型检查的编程语言,尤其是那些具有鸭子类型性质的编程语言。

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.

最美不过初阳 2024-12-05 21:36:20
dictionary_name={key1:value1,key2:value2,key3:value3}
dictionary_name.values()
dictionary_name={key1:value1,key2:value2,key3:value3}
dictionary_name.values()
弃爱 2024-12-05 21:36:20

普通 Dict.values()

将返回类似这样的

内容 dict_values(['value1'])

dict_values(['value2'])

如果您只想使用值

  • 使用此

list(Dict.values())[0]< /strong> # 在列表下

Normal Dict.values()

will return something like this

dict_values(['value1'])

dict_values(['value2'])

If you want only Values use

  • Use this

list(Dict.values())[0] # Under the List

埋情葬爱 2024-12-05 21:36:19

如果您只需要字典键 123,请使用:your_dict.keys()

如果您只需要字典值 -0.3246-0.9185-3985,请使用:your_dict.values()

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

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), ...].

兮颜 2024-12-05 21:36:19

使用values()

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

>>> d.values()
<<< [-0.3246, -0.9185, -3985]

Use values()

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

>>> d.values()
<<< [-0.3246, -0.9185, -3985]
强者自强 2024-12-05 21:36:19

对于 Python 3,您需要:

list_of_dict_values = list(dict_name.values())

For Python 3, you need:

list_of_dict_values = list(dict_name.values())
辞旧 2024-12-05 21:36:19

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

dict_name_goes_here.values()

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

dict_name_goes_here.keys()

如果您想要所有项目(键和值),我将使用此:

dict_name_goes_here.items()

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()
左耳近心 2024-12-05 21:36:19

对于嵌套字典、字典列表和列出字典的字典,...您可以使用

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:是的,我喜欢yield。 ;-)

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

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 

An example:

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']

Big thanks to @vicent for pointing out that strings are also Iterable! I updated my answer accordingly.

PS: Yes, I love yield. ;-)

波浪屿的海角声 2024-12-05 21:36:19

在字典上调用 values() 方法。

Call the values() method on the dict.

羁〃客ぐ 2024-12-05 21:36:19

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

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

I know this question been asked years ago but its quite relevant even today.

>>> d = {1:-0.3246, 2:-0.9185, 3:-3985}
>>> l = list(d.values())
>>> l
[-0.3246, -0.9185, -3985]
糖果控 2024-12-05 21:36:19

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

dict_name_goes_here.values()

If you want all of the values, use this:

dict_name_goes_here.values()
川水往事 2024-12-05 21:36:19

包含字典的python文件的代码

dict={"Car":"Lamborghini","Mobile":"iPhone"}
print(dict)

如果你想只打印值(而不是键),那么你可以使用:

dict={"Car":"Lamborghini","Mobile":"iPhone"}
for thevalue in dict.values():
    print(thevalue)

这将只打印字典中的值而不是键

奖励:如果有一个字典,其中的值存储在列表中,如果您只想在新行上打印值,那么您可以使用:

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")

Reference - Narendra Dwivedi - 仅从字典中提取值

Code of python file containing dictionary

dict={"Car":"Lamborghini","Mobile":"iPhone"}
print(dict)

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)

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")

Reference - Narendra Dwivedi - Extract Only Values From Dictionary

无人问我粥可暖 2024-12-05 21:36:19
d = <dict>
values = d.values()
d = <dict>
values = d.values()
表情可笑 2024-12-05 21:36:19

要查看键:

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

要获取每个键引用的值:

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

添加到列表:

for key in d.keys():
    mylist.append(d[key])

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])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文