[英]Retrieving value from this dictionary of tuples
I have a tuple of dictionary that looks like this; 我有一个像这样的字典元组;
names_dict = {0: ('CV', '4'), 1: ('PR', '8'), 2: ('SC', '2'), 3: ('SR', '3'), 4: ('SP', '7'), 5: ('Temperature', '1')}
Next I have this variable which tells me what to retrieve; 接下来,我有一个变量,它告诉我要检索什么;
name = 'Temperature'
I have this function retrieve_value(names_dict , name)
such that when name is 'Temperature'
, the function returns 1. If name is 'SP'
, the function returns 7. 我有此函数
retrieve_value(names_dict , name)
,使得当name为'Temperature'
,该函数返回1。如果name为'SP'
,则该函数返回7。
How can the function be done in python? 该函数如何在python中完成? I am using python 2.7.9
我正在使用python 2.7.9
try like this: 尝试这样:
>>> next((value[1] for value in names_dict.values() if value[0]==name), None)
'1'
create a function: 创建一个函数:
>>> def my_function(my_dict, name):
... return next((value[1] for value in my_dict.values() if value[0]==name), None)
...
>>> my_function(names_dict, 'Temperature')
'1'
>>> my_function(names_dict, 'SP')
'7'
You can write a list comprehension and retrieve the first element: 您可以编写列表推导并检索第一个元素:
>>> next(value[1] for value in names_dict.itervalues() if value[0] == 'CV')
'4'
That will raise a StopIteration
if the key you provide isn't found, but you can add a default if you prefer: 如果找不到您提供的密钥,则会引发
StopIteration
,但是您可以根据需要添加默认值:
>>> next((value[1] for value in names_dict.itervalues() if value[0] == 'XXX'), None)
>>>
You can iterate over the values of your dict using dict.values
, which returns a list containing your dict values, just as @Hackaholic answered. 可以遍历使用字典的值
dict.values
,返回包含您的字典值的列表,就像@Hackaholic回答。
In case the dict is too large, that dict.values
may be inefficient, use dict.itervalues
instead, which returns an iterator over the values of your dict but not a list 万一字典太大,这
dict.values
可能是低效的,使用dict.itervalues
代替,这在你的字典的值返回一个迭代器而不是列表
In python3, things are changed. 在python3中,情况发生了变化。
dict.values
returns an iterator but not a list any more. dict.values
返回一个迭代器,但不再返回列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.