I have an array, say:
products = [['product_1','description 1'],['product_2','description 2']]
And I want to check input against the keys, eg,:
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?
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
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']]}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.