如何从python中的字典中检索特定数据

时间:2018-04-27 14:21:35

标签: python dictionary

我有一本字典

product_list = {'Name': ['Milk, 2 Litres', 'Bread', 'Sugar', 'Apple'], 'Price': ['2.0', '3.5', '3.0', '4.5'], 'weight': ['2', '0.6', '2.8', '4.2']} <br/>
Now the Question is <br/>
class Weightcheck:<br/>
    def bag_products(product_list):<br/>
       bag_list = []<br/>
        non_bag_items = []<br/>
        MAX_BAG_WEIGHT = 5.0<br/>

        for product in product_list:
            if product.weight > MAX_BAG_WEIGHT:
                product_list.remove(product)
                non_bag_items.append(product)

每当我将一个参数传递给函数时,

demo = Weightcheck()
demo.bag_products(product_list)

我收到此错误:

  

TypeError:bag_products()需要1个位置参数但是2个被赋予

1 个答案:

答案 0 :(得分:0)

您错过了在self中添加bag_products

替换

def bag_products(product_list):

def bag_products(self, product_list):

根据评论进行编辑

product_list = {'Name': ['Milk, 2 Litres', 'Bread', 'Sugar', 'Apple'], 'Price': ['2.0', '3.5', '3.0', '4.5'], 'weight': ['2', '0.6', '2.8', '4.2']}

class Weightcheck:
    def bag_products(self, product_list):
        bag_list = []
        non_bag_items = []
        MAX_BAG_WEIGHT = 5.0

        for w in product_list['weight']:
            if float(w) > MAX_BAG_WEIGHT:
                bag_list.append(w)
                non_bag_items.append(w)
        print(bag_list)
        print(non_bag_items)

demo = Weightcheck()
demo.bag_products(product_list)