【问题标题】:I want to write a for loop adding a new key to a dictionary with one condition, number of purchases have to be >=3我想编写一个for循环,在一个条件下向字典添加一个新键,购买次数必须> = 3
【发布时间】:2021-07-10 13:08:41
【问题描述】:
customers = {

'customer 1':{'name': 'John Smith', 'city': 'New York', 'nr_or_purchases': 3, 'items':['coffee', 'cookies', 'milk']},

'customer 2':{'name': 'Rebeca Collins', 'city': 'New York', 'nr_or_purchases': 1, 'items':['sugar']},

'customer 3':{'name': 'Edward Matthews', 'city': 'Boston', 'nr_or_purchases': 4, 'items':['bananas', 'apples', 'oranges', 'cherries' ]},

'customer 4':{'name': 'Maria Simmons', 'city': 'Boston', 'nr_or_purchases': 3, 'items':['ham', 'cheese', 'butter']}}

我想编写一个 for 循环,为每个购买超过 3 次的客户添加一个名为 'promo' : 'coupon' 的新键

【问题讨论】:

    标签: python loops dictionary for-loop conditional-statements


    【解决方案1】:
    for customer in customers: # loop through your customers dictionary
        if customers[customer]["nr_or_purchases"] > 3: # check the item for a condition
            customers[customer]["promo"] = "coupon" # if the condition applies, do something
    

    此外,如果您的字典的主要标签将是“客户 1”、“客户 2”等(即有序元素),您应该使用字典数组而不是字典字典。

    【讨论】:

      猜你喜欢
      • 2019-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-13
      • 2020-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多