简体   繁体   中英

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.

How can the function be done in python? I am using 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:

>>> 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.

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

In python3, things are changed. dict.values returns an iterator but not a list any more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM