Python 字典在不知道键的情况下获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33709331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:49:46  来源:igfitidea点击:

Dictionary get value without knowing the key

pythondictionary

提问by Yunti

In python if I have a dictionary which has a single key value pair and if I don't know what the key might be, how can I get the value?

在 python 中,如果我有一个只有一个键值对的字典,如果我不知道键可能是什么,我怎么能得到这个值?

(and if I have a dict with more than 1 key, value pair, how can I return any one of the values without knowing any of the keys?)

(如果我有一个超过 1 个键、值对的字典,我如何在不知道任何键的情况下返回任何一个值?)

采纳答案by Delgan

You just have to use dict.values().

你只需要使用dict.values().

This will return a list containing all the values of your dictionary, without having to specify any key.

这将返回一个包含字典所有值的列表,而无需指定任何键。

You may also be interested in:

您也可能对。。。有兴趣:

  • .keys(): return a list containing the keys
  • .items(): return a list of tuples (key, value)
  • .keys(): 返回一个包含键的列表
  • .items(): 返回元组列表 (key, value)

Note that in Python 3, returned value is not actually proper list but view object.

请注意,在 Python 3 中,返回值实际上不是正确的列表,而是视图对象

回答by cssyphus

Further to Delgan's excellent answer (please upvote his answer instead of this one), here is an example for Python 3 that demonstrates how to use the view object:

除了 Delgan 的出色答案(请对他的答案而不是这个答案投赞成票,这里是 Python 3 的一个示例,它演示了如何使用视图对象:

In Python 3 you can print the values, without knowing/using the keys, thus:

在 Python 3 中,您可以在不知道/使用键的情况下打印值,因此:

for item in my_dict:
    print( list( item.values() )[0] )

Example:

例子:

    cars = {'Toyota':['Camry','Turcel','Tundra','Tacoma'],'Ford':['Mustang','Capri','OrRepairDaily'],'Chev':['Malibu','Corvette']}
    vals = list( cars.values() )
    keyz = list( cars.keys() )
    cnt = 0
    for val in vals:
        print('[_' + keyz[cnt] + '_]')
        if len(val)>1:
            for part in val:
                print(part)
        else:
            print( val[0] )
        cnt += 1

    OUTPUT:
    [_Toyota_]
    Camry
    Turcel
    Tundra
    Tacoma
    [_Ford_]
    Mustang
    Capri
    OrRepairDaily
    [_Chev_]
    Malibu
    Corvette

That Py3 docs reference again:

该 Py3 文档再次参考:

https://docs.python.org/3.5/library/stdtypes.html#dict-views

https://docs.python.org/3.5/library/stdtypes.html#dict-views