Ollie
Ollie

Reputation: 67

Python - return first value for each key

Can someone help possibly point out a way of retrieving the first value for each key in a defaultdict/dictionary?

For example I have this less than elegant solution:

d = {'4089e04a': ['24.0', '24.0', '24.0', '23.93', '23.93
', '23.93'], '408b2e00': ['20.91', '33.33'], '408b2e0c': ['44.44']}

print d.values()[0][0]
print d.values()[1][0]
print d.values()[2][0]

It does work - but is there a better way so that I'm not limited to only returning 3 values? I can't work out how to get it working within specifying each key individually...

Thanks

Upvotes: 1

Views: 7436

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251186

d.values() returns a list(py 2x) or views(py3x), you can iterate over it's each item and simply print item[0]

In [165]: d = {'4089e04a': ['24.0', '24.0', '24.0', '23.93', '23.93', '23.93'], '408b2e00': ['20.91', '33.33'], '408b2e0c': ['44.44']}

In [167]: for item in d.values():
   .....:     print item[0]
   .....:     
24.0
20.91
44.44

Upvotes: 1

Sheng
Sheng

Reputation: 3555

Try this

>>> d = {'4089e04a': ['24.0', '24.0', '24.0', '23.93', '23.93',\
'23.93'], '408b2e00': ['20.91', '33.33'], '408b2e0c': ['44.44']}
>>> [item[0] for item in d.values()]
['24.0', '20.91', '44.44']

Hope it helps!

Upvotes: 8

Related Questions