Python Forum

Full Version: extracting second values elements only in every keys in an OrderedDict
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i have this code, i want to extract the second values elements only in every keys in an OrderedDict,
i dont want to use for loop,any idea on this ?
from collections import OrderedDict

regDict= OrderedDict()
regDict["glenn"] = (100,200)
regDict["elena"] = (10,20)
print("values",list(regDict.values())[0][1])
print("values",list(regDict.values())[1][1])
print:
values 200
values 20
target output:
values 200,20    # or values ( 200,20 )
Straight forward with a list comprehension:
from collections import OrderedDict

regDict = OrderedDict([('glenn', (100, 200)), ('elena', (10, 20))])
second_values = [vals[1] for vals in regDict.values()]
There are other methods like using itemgetter and map.
from collections import OrderedDict
from operator import itemgetter

regDict = OrderedDict([('glenn', (100, 200)), ('elena', (10, 20))])
getter = itemgetter(1)
second_values = list(map(getter, regDict.values()))
glennford49 Wrote:i dont want to use for loop
Why don't you want to use for loop? Where does this requirement come from?
(Nov-11-2020, 02:25 PM)Gribouillis Wrote: [ -> ]Where does this requirement come from?

From the teacher, I guess.
What I posted with map is also a loop, but hidden in C.
thanks, +1, this saves my day