Is there a way to return / print a list item without quotes or brackets?

Sorry if this has already been mentioned somewhere (I could not find it).

I basically want to list an item from a list, but include quotes and brackets (which I don't want). Here is my details:

inputData = {'red':3, 'blue':1, 'green':2, 'organge':5} 

Here is my class for finding items 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 by replacing the brackets / quotes ( LookupVariable.replace("'", "") ), but I was wondering if there is an even more pythonic way to do this.

Thanks.

+4
source share
2 answers

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) 

Now you return the result of understanding the list - a list . Instead, you want to return the first element returned by the equivalent generator expression, which is what next does.

Edit: If you really want multiple elements, use Greg's answer - but it sounds to me as if you are only thinking about getting one key - this is a good way to do this.

If you want it to raise a StopIteration error if the value does not exist, leave it as above. If you want something else to be returned instead (e.g. None ):

 return next((item[0] for item in self.items() if item[1] == value), None) 
+4
source

You print the return value of a list that Python formats contain brackets and quotation marks. To print only the first item from a list:

 print Lookup.get_key(2)[0] 

To print list items separated by commas:

 print ", ".join(str(x) for x in Lookup.get_key(2)) 

or

 print ", ".join(map(str, Lookup.get_key(2))) 
+3
source

All Articles