Amar Agrawal
Amar Agrawal

Reputation: 141

Getting single value from multiple values in dictionary

I have a dictionary like this

dic={10:(1,4),20:(2,4),30:(3,4)}

how to get 1,2,3 as output using dic.values() without using for loop.

Upvotes: 0

Views: 1704

Answers (5)

user2555451
user2555451

Reputation:

This works:

>>> dic={10:(1,4),20:(2,4),30:(3,4)}
>>> [x[0] for x in dic.values()]
[1, 2, 3]
>>> # Or if you want that as a tuple
>>> tuple(x[0] for x in dic.values())
(1, 2, 3)
>>> # Or a string
>>> ",".join([str(x[0]) for x in dic.values()])
'1,2,3'
>>>

You should remember though that the order of dictionaries is not guaranteed. Meaning, the key/value pairs will not always be in the same order the you put them in.

To get disordered results in the order you want, you should look at sorted.

Upvotes: 5

dawg
dawg

Reputation: 104102

If you look at what dic.values() produces:

>>> dic={10:(1,4),20:(2,4),30:(3,4)}
>>> dic.values()
[(1, 4), (2, 4), (3, 4)]

Obviously you want the first element of each tuple.

You can use zip to get that without looping1.

>>> zip(*dic.values())[0]
(1, 2, 3)

As pointed out in comments, an even more efficient solution is:

>>> from itertools import izip
>>> next(izip(*dic.itervalues()))
(1, 2, 3)

Then you do not have to go all the way though creating several lists just to get the first element.

The order, of course, depends on the order of the keys in dic.

1 The 'without looping' is a silly distinction IMHO. Every solution either has an explicit or implicit loop in it...

Upvotes: 2

Arovit
Arovit

Reputation: 3719

How about using map here.

map(lambda x: x[0], dic.values())

Upvotes: 0

Don
Don

Reputation: 17636

This solution is not any better than using iterators, but it has a different approach and maybe it is more suitable for complex tasks:

from operator import itemgetter
dic={10:(1,4),20:(2,4),30:(3,4)}
print map(itemgetter(0), dic.values())

gives:

[1, 2, 3]

Upvotes: 0

aIKid
aIKid

Reputation: 28342

Answer: You can't. You'll have to loop through the dictionary:

for v in d.values():
    print v[0]

Or using a list comprehension:

[v[0] for v in d.values()]

This filtering methods are the best you can find :)

Upvotes: 1

Related Questions