The Python dictionary gets the first value of the tuple

The Python dictionary gets the first value of the tuple … here is a solution to the problem.

The Python dictionary gets the first value of the tuple

I have a dictionary-

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

I only want to get the first value of each tuple, which is 0 in this case.

p["a"] 

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

Solution

Maybe 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]

Related Problems and Solutions