【问题标题】:Nested Dictionary for loop嵌套字典 for 循环
【发布时间】:2020-09-13 22:29:21
【问题描述】:

我是编程新手。我试图弄清楚如何从“实际”中减去“预算”,然后使用嵌套的 for 循环将值更新为“方差”。但是,我读过在迭代时更改字典并不是最佳实践。到目前为止,我一直不知道如何进行。

for i in properties:
    for j in properties[i]:
        if j == "actual":
            sum = properties[i][j]
            print('\nActual:' , sum)
        if j == "budgeted":
            sum_two = properties[i][j]
            print('Budgeted:' , sum_two)
            diff = sum_two - sum
            print('Variance:', diff)    
default_value = 0

properties = {587: {'prop_name': 'Collington'}, 'rental_income': {'apartment_rent': '5120-0000', 'resident_assistance': '5121-0000', 'gain_loss': '5120-0000'}, 51200000: {'actual': 29620, 'budgeted': 30509, 'variance': default_value}, 51210000: {'actual': 25620, 'budgeted': 40509, 'variance': default_value}, ............

【问题讨论】:

  • 您可以在迭代字典时更新字典中的值。您不应该做的是删除或插入新值。

标签: python dictionary for-loop nested


【解决方案1】:

只需遍历字典并检查内部字典中是否存在actualvariancebudgeted是否存在,如果存在则修改variance

for k, v in properties.items():
    if (('actual' in v.keys()) and ('variance' in v.keys()) and ('budgeted' in v.keys())):
            properties[k]['variance'] = properties[k]['actual']-properties[k]['budgeted']

【讨论】:

    【解决方案2】:

    在迭代时修改字典内部的值并没有错。唯一不推荐的是修改字典本身,即添加/删除元素。

    【讨论】:

      【解决方案3】:

      尝试类似:

      for i in properties:
          properties[i]['variance'] = properties[i]['budgeted'] - properties[i]['actual']
      

      如果您不确定字典中是否存在bugetedactual,则应捕获 KeyError 并适当处理:

      for i in properties:
          try:
              properties[i]['variance'] = properties[i]['budgeted'] - properties[i]['actual']
          except KeyError:
              properties[i]['variance'] = -1 # Set to some special value or just pass
      

      【讨论】:

      • 你不能用dict.get()代替try块吗?
      • 有些人会争辩说,先尝试,然后再请求宽恕,这更像是pythonic:stackoverflow.com/a/12265860/5075269
      • 但是如果假设不存在 variance 或者不存在,那么使用 try 和 except 会增加很多时间,而且它还会创建一个新键 variance,其中甚至不需要方差,所以使用 @987654329 @是更好的选择
      【解决方案4】:

      您的数据格式很奇怪,我总是尝试在字典中将类似的对象组合在一起,而不是在字典的同一级别中包含元数据和项目的“列表”。不过这对你有用:

      for prop in properties:
          p = properties[prop]
          if 'actual' or 'budgeted' in p.keys():
              # get() wont error if not found, also default to 0 if not found
              p['variance'] = p.get('budgeted', 0) - p.get('actual', 0)
      
      import json
      print(json.dumps(properties, indent=4))
      
      

      输出:

      {
          "587": {
              "prop_name": "Collington"
          },
          "rental_income": {
              "apartment_rent": "5120-0000",
              "resident_assistance": "5121-0000",
              "gain_loss": "5120-0000"
          },
          "51200000": {
              "actual": 29620,
              "budgeted": 30509,
              "variance": 889
          },
          "51210000": {
              "actual": 25620,
              "budgeted": 40509,
              "variance": 14889
          }
      }
      

      【讨论】:

        【解决方案5】:
        sum = None
        sum_two = None
        for i in properties:
                for j in i:
                    if j=="actual":
                        sum = properties [i]["actual"] 
                        print('\nActual:' , sum)
                    if j == "budgeted":
                        sum_two = properties[i]["budgeted"]
                        print('Budgeted:' , sum_two)
                        diff = sum_two - sum
                        print('Variance:', diff)
        

        我不明白到底是什么意思,但这应该可以。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-07-25
          • 2019-03-29
          • 2022-01-03
          • 1970-01-01
          • 1970-01-01
          • 2017-07-22
          相关资源
          最近更新 更多