Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 循环嵌套字典_Python_Dictionary_For Loop_Nested - Fatal编程技术网

Python 循环嵌套字典

Python 循环嵌套字典,python,dictionary,for-loop,nested,Python,Dictionary,For Loop,Nested,我是编程新手。我试图找出如何从“实际”中减去“预算”,然后使用嵌套for循环将值更新为“方差”。然而,我读到,在迭代时更改字典并不是最佳做法。到目前为止,我一直不知道如何继续下去 for i in properties: for j in properties[i]: if j == "actual": sum = properties[i][j] print('\nActual:' , sum) if j

我是编程新手。我试图找出如何从“实际”中减去“预算”,然后使用嵌套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)    

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

试试以下方法:

for i in properties:
    properties[i]['variance'] = properties[i]['budgeted'] - properties[i]['actual']
如果您不确定字典中是否存在
bugged
actual
,则应捕获关键错误并正确处理:

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

我不明白确切的意思,但这应该行得通

只需遍历字典,检查内部字典中是否存在
实际值
差异
预算值
,如果存在,则修改
差异

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']

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

属性中的道具:
p=属性[prop]
如果p.keys()中的“实际”或“预算”:
#如果找不到get(),则不会出错;如果找不到,则默认为0
p['variance']=p.get('预算',0)-p.get('实际',0)
导入json
打印(json.dumps(属性,缩进=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
    }
}

可以在迭代字典时更新字典中的值。您不应该做的是删除或插入新值。您不能使用
dict.get()吗
而不是try块?有些人会争辩说,先尝试,然后再请求原谅更像是python:但是如果假设不存在差异,那么使用try and except会增加很多时间,并且它还会创建一个新的键
差异
,其中甚至不需要差异,因此使用
if x在dic.keys()中
是更好的选择
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']
{
    "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
    }
}