Reputation: 26067
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.
Upvotes: 4
Views: 9976
Reputation: 176980
Change
return [item[0] for item in self.items() if item[1] == value]
to
return next(item[0] for item in self.items() if item[1] == value)
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 what next
does.
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 StopIteration
error if the value doesn't exist, leave it as above. If you want it to return something else instead (like None
) do:
return next((item[0] for item in self.items() if item[1] == value), None)
Upvotes: 4
Reputation: 994877
You're printing the returned list value, which Python formats with brackets and quotes. To print just the first element from the list:
print Lookup.get_key(2)[0]
To print the elements of the list separated by commas:
print ", ".join(str(x) for x in Lookup.get_key(2))
or
print ", ".join(map(str, Lookup.get_key(2)))
Upvotes: 3