Sorry if this is already mentioned somewhere(I couldn’t find it).
I basically want to list an item from a list but its including quotes and brackets(which I don’t want).
Here’s my data:
inputData = {'red':3, 'blue':1, 'green':2, 'organge':5}
Here’s my class to find items either based on key or value.
class Lookup(dict):
"""
a dictionary which can lookup value by key, or keys by value
"""
def __init__(self, items=[]):
"""items can be a list of pair_lists or a dictionary"""
dict.__init__(self, items)
def get_key(self, value):
"""find the key(s) as a list given a value"""
return [item[0] for item in self.items() if item[1] == value]
def get_value(self, key):
"""find the value given a key"""
return self[key]
it works fine except for the brackets.
print Lookup().get_key(2) # ['blue'] but I want it to just output blue
I know I can do this via replacing the bracket/quotes( LookupVariable.replace("'", "") ) but I was wondering if there was a more pythonic way of doing this.
Thanks.
Change
to
Right now you’re returning the result of a list comprehension — a
list. Instead, you want to return the first item returned by the equivalent generator expression — that’s whatnextdoes.Edit: If you actually want multiple items, use Greg’s answer — but it sounds to me like you’re only thinking about getting a single key — this is a good way to do that.
If you want it to raise a
StopIterationerror if the value doesn’t exist, leave it as above. If you want it to return something else instead (likeNone) do: