比较python中的字典键和值的方法

时间:2017-05-10 15:52:40

标签: python-2.7 dictionary

我有:

dictionary1 = {'Zookeeper': 3, 'Profit': 3, 'Collector': 3, 'Service': 3}

dictionary2 = {'Zookeeper': 2, 'Profit': 2}

dictionary2的长度可能相同,也可能不同,可能与dictionary1具有相同或不同的值。如何编写Python函数来比较这些词典并打印dictionary2中与dictionary1值不匹配的键?

我想出了这个只与键匹配的内容:

check_result = set(dictionary1.keys()) == set(dictionary2.keys())

但我需要更精确的东西。

2 个答案:

答案 0 :(得分:3)

最后我明白了你的问题,这应该做的工作:

dictioanry1 = {'Zookeeper': 3, 'Profit': 3, 'Collector': 3, 'Service': 3}
dictionary2 = {'Zookeeper': 2, 'Profit': 2}

A = list(dictioanry1.keys())
B = list(dictionary2.keys())
commonKeys = set(A) - (set(A) - set(B))


for key in commonKeys:
    if(dictioanry1[key] != dictionary2[key]):
      print (key + ":" + str(dictionary2[key]) + " should be " + str(dictioanry1[key]))

   $ Profit:2 should be 3
   $ Zookeeper:2 should be 3

commonKeys是匹配的键,好吗?和A是dictionary1.keys()(我把它们变成两个变量更多的claire)所以,我想打印来自dictionary2(或B)的所有值,但是不匹配,所以,你问是否属于匹配清单

答案 1 :(得分:1)

我正在解决类似的问题并使用了一个可以在这里适用的解决方案。

如果你想从dictionary2打印与dictionary1的值不匹配的键,你可以尝试这样的事情

ServiceClientCredentials serviceCreds = 
   await ApplicationTokenProvider.LoginSilentAsync(this.config.ADTenant, this.config.ADApplicationId, this.config.ADKey);

ResourceManagementClient resourceClient = new ResourceManagementClient(serviceCreds);
resourceClient.SubscriptionId = this.config.SubscriptionId;
WebSiteManagementClient webClient = new WebSiteManagementClient(serviceCreds);
webClient.SubscriptionId = this.config.SubscriptionId;

string urlPath = "custompath/";
SiteInner site = 
   webClient.WebApps.List().Where(a => a.Id == "webapp id").FirstOrDefault();
IList<SiteInstanceInner> instances = 
   webClient.WebApps.ListInstanceIdentifiers(site.ResourceGroup, site.Name).ToList();

SiteInstanceInner instance = instances.FirstOrDefault();

// these are initialized as a singleton, inline here as an example
HttpClientHandler handler = new HttpClientHandler() { UseCookies = false };
HttpClient httpClient = new HttpClient(handler, disposeHandler: false);

httpClient.Timeout = new TimeSpan(0, 0, 30);
webClient = await GetWebsiteClientIfNull(webClient);

Uri url = new Uri($"http://{site.DefaultHostName}/{urlPath}");

HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Get, url);
message.Headers.Add("Arr-Enable-Session-Affinity", bool.TrueString);
message.Headers.Add("Cookie", $"ARRAffinity={WebUtility.UrlEncode(instance.Name)};");

HttpResponseMessage response = await webClient.HttpClient.SendAsync(message);

只返回来自dictionary2的键,当你提出问题时,这些键与dictionary1的值不匹配。在我的例子中,我发现将键和不匹配的值作为字典返回更有益:

>>> dictionary1 = {'Zookeeper': 3, 'Profit': 3, 'Collector': 3, 'Service': 3}
>>> dictionary2 = {'Zookeeper': 2, 'Profit': 2}
>>> [ key for key, val in dictionary2.items() if dictionary1.get(key, None) != val ]
['Zookeeper', 'Profit']