微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python字典的问题

如何解决python字典的问题

我有简单的 python 脚本。 当我做这个时,我的字典中的所有内容OK

import json

blueprint={'byolOnDedicatedInstance': False,'disks': [{'iops': 46600,'name': 'c:0','throughput': 0,'type': 'PROVISIONED_SSD'}],'forceUEFI': False,'iamRole': '','id': '755c7877-0855-4b5b-a777-8e5544e81ea5','instanceType': 'copY_ORIGIN','machineId': 'b20a601a-84a1-4d77-8bwe-we123456ce4c8','networkInterface': '','placementGroup': '','privateIPAction': 'copY_ORIGIN','privateIPs': [],'publicIPAction': 'ALLOCATE','recommendedInstanceType': 'c4.4xlarge','recommendedPrivateIP': '192.168.1.1','region': '71fbc55-a3a8-4111-45gb-3db3353a53ea','runAfterLaunch': True,'securityGroupIDs': [],'staticIp': '','staticIpAction': 'DONT_CREATE','subnetIDs': [],'subnetsHostProject': '','tags': [],'tenancy': 'SHARED','myinstancetype': 'None'}
print(blueprint)

blueprint_value={'byolOnDedicatedInstance': False,'myinstancetype': 'None','disks': [{'iops': 0,'type': 'SSD'}],'instanceType': 'm5.xlarge','privateIPAction': 'CREATE_NEW','publicIPAction': 'DONT_ALLOCATE','securityGroupIDs': ['sg-0aab4ed55ae11f8ec'],'subnetIDs': ['subnet-0c1bawae4656e777d'],'tenancy': 'HOST'}
print(blueprint_value)

patch = { key: blueprint_value[key]
            for key in blueprint_value.keys()
            if blueprint_value[key] != blueprint[key]
        }
print(patch)

一切正常,我收到了需要的文本:

{'disks': [{'iops': 0,'tenancy': 'HOST'}

当我向第二个值 (blueprint_value) 添加附加元素 ('dedicatedHostIdentifier': 'h-02d121f9u77d7a123') 时,我收到错误

Traceback (most recent call last):
  File "/home/test/test/1.py",line 8,in <module>
    patch = { key: blueprint_value[key]
  File "/home/test/test/1.py",line 10,in <dictcomp>
    if blueprint_value[key] != blueprint[key]
KeyError: 'dedicatedHostIdentifier'

不工作版本的全文:

import json

blueprint={'byolOnDedicatedInstance': False,'dedicatedHostIdentifier': 'h-02d121f9u77d7a123','tenancy': 'HOST'}
print(blueprint_value)

patch = { key: blueprint_value[key]
            for key in blueprint_value.keys()
            if blueprint_value[key] != blueprint[key]
        }
print(patch)

用于比较 blueprint_valueblueprint 变量中的两个 JSON-s 和返回元素的脚本的主要思想。

解决方法

使用 dict.get(key) 如果键不存在它只会返回 None 这是默认值并且不会出错,所以这个条件 if blueprint_value.get(key) != blueprint.get(key) 不会导致 {{1} } .如果您有 KeyError 的默认值,您也可以提供该值。

dedicatedHostIdentifier
>>> x= {}
>>> x.get("ok")
>>> y = x.get("ok")
>>> print(y)
None
>>> y = x.get("ok","not")
>>> y
'not'

Why dict.get(key) instead of dict[key]?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。