【问题标题】:Problems with python dictionarypython字典的问题
【发布时间】:2021-03-06 21:47:47
【问题描述】:

我有简单的 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, 'name': 'c:0', 'throughput': 0, 'type': 'SSD'}], 'forceUEFI': False, 'iamRole': '', 'id': '755c7877-0855-4b5b-a777-8e5544e81ea5', 'instanceType': 'm5.xlarge', 'machineId': 'b20a601a-84a1-4d77-8bwe-we123456ce4c8', 'networkInterface': '', 'placementGroup': '', 'privateIPAction': 'CREATE_NEW', 'privateIPs': [], 'publicIPAction': 'DONT_ALLOCATE', 'recommendedInstanceType': 'c4.4xlarge', 'recommendedPrivateIP': '192.168.1.1', 'region': '71fbc55-a3a8-4111-45gb-3db3353a53ea', 'runAfterLaunch': True, 'securityGroupIDs': ['sg-0aab4ed55ae11f8ec'], 'staticIp': '', 'staticIpAction': 'DONT_CREATE', 'subnetIDs': ['subnet-0c1bawae4656e777d'], 'subnetsHostProject': '', 'tags': [], '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, 'name': 'c:0', 'throughput': 0, 'type': 'SSD'}], 'instanceType': 'm5.xlarge', 'privateIPAction': 'CREATE_NEW', 'publicIPAction': 'DONT_ALLOCATE', 'securityGroupIDs': ['sg-0aab4ed55ae11f8ec'], 'subnetIDs': ['subnet-0c1bawae4656e777d'], '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, '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', 'dedicatedHostIdentifier': 'h-02d121f9u77d7a123', 'disks': [{'iops': 0, 'name': 'c:0', 'throughput': 0, 'type': 'SSD'}], 'forceUEFI': False, 'iamRole': '', 'id': '755c7877-0855-4b5b-a777-8e5544e81ea5', 'instanceType': 'm5.xlarge', 'machineId': 'b20a601a-84a1-4d77-8bwe-we123456ce4c8', 'networkInterface': '', 'placementGroup': '', 'privateIPAction': 'CREATE_NEW', 'privateIPs': [], 'publicIPAction': 'DONT_ALLOCATE', 'recommendedInstanceType': 'c4.4xlarge', 'recommendedPrivateIP': '192.168.1.1', 'region': '71fbc55-a3a8-4111-45gb-3db3353a53ea', 'runAfterLaunch': True, 'securityGroupIDs': ['sg-0aab4ed55ae11f8ec'], 'staticIp': '', 'staticIpAction': 'DONT_CREATE', 'subnetIDs': ['subnet-0c1bawae4656e777d'], 'subnetsHostProject': '', 'tags': [], 'tenancy': 'HOST'}
print(blueprint_value)

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

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

【问题讨论】:

  • 你的预期输出是什么?
  • 我展示了{'disks': [{'iops': 0, 'name': 'c:0', 'throughput': 0, 'type': 'SSD'}], 'instanceType': 'm5.xlarge', 'privateIPAction': 'CREATE_NEW', 'publicIPAction': 'DONT_ALLOCATE', 'securityGroupIDs': ['sg-0aab4ed55ae11f8ec'], 'subnetIDs': ['subnet-0c1bawae4656e777d'], 'tenancy': 'HOST'}
  • 我必须收到相同的,但在 JSON 'dedicatedHostIdentifier': 'h-02d121f9u77d7a123' 中有额外的元素@
  • @Piduna 两个字典的长度各不相同。 len(blueprint) =&gt; 24len(blueprint_value) =&gt; 25 正在一对一进行比较。因此,在一种情况下,名为blueprint 的字典之一中没有对应的键。因此出现错误。

标签: python json dictionary compare


【解决方案1】:

使用 dict.get(key) 如果密钥不存在,它将简单地返回 None 这是默认值并且不会出错,所以这个条件 if blueprint_value.get(key) != blueprint.get(key) 不会导致 KeyError 。如果您有 dedicatedHostIdentifier 的默认值,您也可以提供它。

>>> x= {}
>>> x.get("ok")
>>> y = x.get("ok")
>>> print(y)
None
>>> y = x.get("ok", "not")
>>> y
'not'
>>> import json
...
... blueprint={'byolOnDedicatedInstance': False, 'disks': [{'iops': 46600, 'name': 'c:0', 'throughput': 0, 'type': 'PROVISIONED_SS
... D'}], 'forceUEFI': False, 'iamRole': '', 'id': '755c7877-0855-4b5b-a777-8e5544e81ea5', 'instanceType': 'COPY_ORIGIN', 'machine
... Id': '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': '', 'staticIpAc
... tion': 'DONT_CREATE', 'subnetIDs': [], 'subnetsHostProject': '', 'tags': [], 'tenancy': 'SHARED', 'myinstancetype': 'None'}
... print(blueprint)
...
... blueprint_value={'byolOnDedicatedInstance': False, 'myinstancetype': 'None', 'dedicatedHostIdentifier': 'h-02d121f9u77d7a123',
...  'disks': [{'iops': 0, 'name': 'c:0', 'throughput': 0, 'type': 'SSD'}], 'forceUEFI': False, 'iamRole': '', 'id': '755c7877-085
... 5-4b5b-a777-8e5544e81ea5', 'instanceType': 'm5.xlarge', 'machineId': 'b20a601a-84a1-4d77-8bwe-we123456ce4c8', 'networkInterfac
... e': '', 'placementGroup': '', 'privateIPAction': 'CREATE_NEW', 'privateIPs': [], 'publicIPAction': 'DONT_ALLOCATE', 'recommend
... edInstanceType': 'c4.4xlarge', 'recommendedPrivateIP': '192.168.1.1', 'region': '71fbc55-a3a8-4111-45gb-3db3353a53ea', 'runAft
... erLaunch': True, 'securityGroupIDs': ['sg-0aab4ed55ae11f8ec'], 'staticIp': '', 'staticIpAction': 'DONT_CREATE', 'subnetIDs': [
... 'subnet-0c1bawae4656e777d'], 'subnetsHostProject': '', 'tags': [], 'tenancy': 'HOST'}
... print(blueprint_value)
...
... patch = { key: blueprint_value.get(key)
...             for key in blueprint_value.keys()
...             if blueprint_value.get(key) != blueprint.get(key)
...         }
... print(patch)
{'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'}
{'byolOnDedicatedInstance': False, 'myinstancetype': 'None', 'dedicatedHostIdentifier': 'h-02d121f9u77d7a123', 'disks': [{'iops': 0, 'name': 'c:0', 'throughput': 0, 'type': 'SSD'}], 'forceUEFI': False, 'iamRole': '', 'id': '755c7877-0855-4b5b-a777-8e5544e81ea5', 'instanceType': 'm5.xlarge', 'machineId': 'b20a601a-84a1-4d77-8bwe-we123456ce4c8', 'networkInterface': '', 'placementGroup': '', 'privateIPAction': 'CREATE_NEW', 'privateIPs': [], 'publicIPAction': 'DONT_ALLOCATE', 'recommendedInstanceType': 'c4.4xlarge', 'recommendedPrivateIP': '192.168.1.1', 'region': '71fbc55-a3a8-4111-45gb-3db3353a53ea', 'runAfterLaunch': True, 'securityGroupIDs': ['sg-0aab4ed55ae11f8ec'], 'staticIp': '', 'staticIpAction': 'DONT_CREATE', 'subnetIDs': ['subnet-0c1bawae4656e777d'], 'subnetsHostProject': '', 'tags': [], 'tenancy': 'HOST'}
{'dedicatedHostIdentifier': 'h-02d121f9u77d7a123', 'disks': [{'iops': 0, 'name': 'c:0', 'throughput': 0, 'type': 'SSD'}], 'instanceType': 'm5.xlarge', 'privateIPAction': 'CREATE_NEW', 'publicIPAction': 'DONT_ALLOCATE', 'securityGroupIDs': ['sg-0aab4ed55ae11f8ec'], 'subnetIDs': ['subnet-0c1bawae4656e777d'], 'tenancy': 'HOST'}
>>>

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 2021-07-24
    • 2019-10-13
    • 2018-02-08
    • 1970-01-01
    相关资源
    最近更新 更多