代码之家  ›  专栏  ›  技术社区  ›  Anuj TBE

如果字典列表中存在键,则获取值

  •  1
  • Anuj TBE  · 技术社区  · 7 年前

    [{'month': 8, 'total': 31600.0}, {'month': 9, 'total': 2000.0}]
    

    [
      {'month': 1, 'total': 0},
      {'month': 2, 'total': 0},
      ...
      {'month': 8, 'total': 31600},
      {'month': 9, 'total': 2000},
      ...
      {'month': 12, 'total': 0}
    ]
    

    (1,13)

    new_list = []
    for i in range(1, 13):
      # if i exists in month, append to new_list
      # else add total: 0 and append to new_list
    

    我怎样才能确认 存在于 去拿字典?

    3 回复  |  直到 7 年前
        1
  •  7
  •   jpw    7 年前

    您可以将dict列表转换为directmonth:total映射

    monthly_totals = {item['month']: item['total'] for item in data_list}
    

    dict.get 要处理缺少的值,请执行以下操作:

    new_list = [{'month': i, 'total': monthly_totals.get(i, 0)} for i in range(1, 13)]
    
        2
  •  1
  •   Sunitha    7 年前

    创建一个包含默认值的新列表,然后从原始列表中更新所需的值

    >>> lst = [{'month': 8, 'total': 31600.0}, {'month': 9, 'total': 2000.0}]
    >>> new_lst = [dict(month=i, total=0) for i in range(1,13)]
    >>> for d in lst:
    ...     new_lst[d['month']-1] = d
    ... 
    >>> pprint(new_lst)
    [{'month': 1, 'total': 0},
     {'month': 2, 'total': 0},
     {'month': 3, 'total': 0},
     {'month': 4, 'total': 0},
     {'month': 5, 'total': 0},
     {'month': 6, 'total': 0},
     {'month': 7, 'total': 0},
     {'month': 8, 'total': 31600.0},
     {'month': 9, 'total': 2000.0},
     {'month': 11, 'total': 0},
     {'month': 12, 'total': 0}]
    
        3
  •  0
  •   Tanmay jain    7 年前
    exist_lst =  [{'month': 8, 'total': 31600.0}, {'month': 9, 'total': 2000.0}]
    
    new_lst = []
    
    for i in range(1,13):
        found = False
        for dict_item in exist_lst:
            if dict_item['month'] == i:
                new_lst.append(dict_item)
                found = True
    
        if not found: 
            new_lst.append({'month': i, 'total': 0}) # default_dict_item
    
    print(new_lst)