I have a n-tuple of dictionaries. I want to retrieve a dictionary from this tuple that contains a particular key-value pair.
I'm trying to do this as elegantly as possible, and I think a list comprehension is the way to go - but this isn't a basic list comprehension and I'm a little lost.
This shows the idea of what I'm trying to do, but it doesn't work of course:
# 'data' is my n-tuple
# 'myKey' is the key I want
# 'myValue is the value I want
result = [data[x] for dictionary in data if (data[x][myKey]) == myValue)][0]
# which gives this error:
NameError: global name 'x' is not defined
Before, I was trying something like this (the error makes sense and I understand it):
result = [data[x] for x in data if (data[x][myKey] == myValue)][0]
# which gives this error:
TypeError: tuple indices must be integers, not dict
Is this a time to use nested comprehensions? What would that look like, and would it be simpler at that point to just write it out with loops and conditionals?
Also, side question - is there a more pythonic way to get the first (or the only) element in a list besides just slapping [0] on the end?