1

I have an array, say:

products = [['product_1','description 1'],['product_2','description 2']]

And I want to check input against the keys, e.g.,:

product = raw_input('Enter product:  ')
if product not in products.keys():
    log.fatal('Invalid product: {}'.format(product))
    exit(1)

keys() doesn't work -- what should I be doing?

2 Answers 2

2

lists dont have keys ... you just want the first element of each sublist

dict(products).keys() #ONLY if there is exactly 2 items per sublist

or

zip(*products)[0] #any number of items per sublist is ok

or

[k for k,val in products] # only if you have EXACTLY 2 items per sublist

or

[item[0] for item in products]  # any number of items in each sublist
Sign up to request clarification or add additional context in comments.

Comments

2

keys is not a method of a list. You must be thinking of a dict. Just do:

products = {k: v for k, v in [['product_1','description 1'],['product_2','description 2']]}

1 Comment

or just call dict on your list directly ... good answer all the same

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.