megna
megna

Reputation: 245

Python dictionary getting first value of tuple

I have a dictionary -

p = {"a": [(0,1),(0,3)]}

I want to fetch only the first value of each tuple i.e, 0 in this case.

p["a"] 

gives me [(0,1),(0,3)] but I want [0,0] Can anyone suggest how to do this?

Upvotes: 3

Views: 4146

Answers (4)

niraj
niraj

Reputation: 18208

May be you can try list comprehension:

p = {"a": [(0,1),(0,3)]}
# key to search
k = 'a'

res = [element[0] for element in p.get(k,[])]
print(res)

Result:

[0, 0]

Upvotes: 1

Vicrobot
Vicrobot

Reputation: 3988

p = {"a": [(0,1),(0,3)]}

for i in p["a"]:
    print(i[0])

Try this one...

Upvotes: 0

Mehrdad Pedramfar
Mehrdad Pedramfar

Reputation: 11073

Try this:

d = {k:[i[0] for i in v] for k,v in p.items()}

> d
{'a': [0, 0]}

Upvotes: 1

erocoar
erocoar

Reputation: 5893

You could just loop over it

[x[0] for x in p["a"]]

Upvotes: 1

Related Questions