如何迭代数组数组中的键?

时间:2016-06-23 19:59:03

标签: python arrays python-2.7

我有一个阵列,说:

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

我想根据键检查输入,例如:

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

keys()不起作用 - 我该怎么办?

2 个答案:

答案 0 :(得分:2)

列出没有键......你只想要每个子列表的第一个元素

getElementById()

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

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

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

答案 1 :(得分:2)

keys不是list的方法。你必须考虑dict。只是做:

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