查找字典差异并转换结果-python3
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了查找字典差异并转换结果-python3相关的知识,希望对你有一定的参考价值。
我对python世界还很陌生,到目前为止,它非常有趣,但是,在下面的用例中发现了困难,我们将提供任何帮助。
我有2个字典,它们具有相同的键但值不同,使用通过对称差异进行设置,我能够从2个字典中获取元组列表,但不确定如何将其转换为我期望的结果。
mydict1 =
"KMSKeyId": "arn:aws:kms:us-east-1:12345:alias/key_name",
"Subnets": "subnet-123,subnet-456",
"VpcId": "vpc-123",
"Region": "us-east-1",
"SecurityGroups": "sg-123,sg-456",
"ProxyHost": "my-custom-proxy-us-east-1.aws.com"
mydict2 =
"KMSKeyId": "arn:aws:kms:us-west-1:12345:alias/key_name",
"Subnets": "subnet-789,subnet-1011",
"VpcId": "vpc-456",
"SecurityGroups": "sg-789,sg-1011",
"Region": "us-west-1",
"ProxyHost": "my-custom-proxy-us-west-1.aws.com"
预期结果
result =
"us-east-1":
"KMSKeyId": "arn:aws:kms:us-east-1:12345:alias/key_name",
"Subnets": "subnet-123,subnet-456",
"VpcId": "vpc-123",
"SecurityGroups": "sg-123,sg-456",
"ProxyHost": "my-custom-proxy-us-east-1.aws.com"
,
"us-west-1":
"KMSKeyId": "arn:aws:kms:us-west-1:12345:alias/key_name",
"Subnets": "subnet-789,subnet-1011",
"VpcId": "vpc-456",
"SecurityGroups": "sg-789,sg-1011",
"ProxyHost": "my-custom-proxy-us-west-1.aws.com"
print(list(set(mydict1.items()) ^ set(mydict2.items()))) yields ---->
[('SecurityGroups', 'sg-789,sg-1011'),
('ProxyHost', 'my-custom-proxy-us-east-1.aws.com'),
('Subnets', 'subnet-123,subnet-456'),
('SecurityGroups', 'sg-123,sg-456'),
('Subnets', 'subnet-789,subnet-1011'),
('KMSKeyId', 'arn:aws:kms:us-west-1:12345:alias/key_name'),
('Region', 'us-east-1'),
('ProxyHost', 'my-custom-proxy-us-west-1.aws.com'),
('VpcId', 'vpc-456'),
('Region', 'us-west-1'),
('KMSKeyId', 'arn:aws:kms:us-east-1:12345:alias/key_name'),
('VpcId', 'vpc-123')]
从上面的元组列表中,不确定如何获得预期的结果。使用此处描述的FakeDict
,https://stackoverflow.com/a/29520802/2101043能够获得具有相同键和不同值的类似dict的对象,但是,作为python的初学者,将VPC,子网和安全组映射到相应的区域似乎具有挑战性
答案
您应该能够使用:
result =
for myMap in [mydict1, mydict2]:
result[myMap["Region"]] = key:myMap[key] for key in myMap if key != "Region"
在打印出结果后,将为您提供所需的内容(为便于阅读而设置格式:]
'us-east-1':
'KMSKeyId': 'arn:aws:kms:us-east-1:12345:alias/key_name',
'Subnets': 'subnet-123,subnet-456',
'VpcId': 'vpc-123',
'SecurityGroups': 'sg-123,sg-456',
'ProxyHost': 'my-custom-proxy-us-east-1.aws.com'
,
'us-west-1':
'KMSKeyId': 'arn:aws:kms:us-west-1:12345:alias/key_name',
'Subnets': 'subnet-789,subnet-1011',
'VpcId': 'vpc-456',
'SecurityGroups': 'sg-789,sg-1011',
'ProxyHost': 'my-custom-proxy-us-west-1.aws.com'
我怀疑您可以可能用一行完成它,但是我认为将其从三行减少到一行的好处有点可疑:-)
以上是关于查找字典差异并转换结果-python3的主要内容,如果未能解决你的问题,请参考以下文章