简体   繁体   English

比较两个字典并打印差异

[英]Compare Two Dictionaries and Print Difference

I have taken the difference between values for two dictionaries.我已经计算了两个字典的值之间的差异。 What I have currently works, but I want to print "dict1[x] - dict2[x]" to the file I write to in front of the results.我目前所做的工作,但我想将“dict1[x] - dict2[x]”打印到我在结果前面写入的文件中。 Not just the results.不仅仅是结果。 How can I do this?我怎样才能做到这一点? Do I need a nested loop?我需要嵌套循环吗?

comparison = {x: dict1[x] - dict2[x] for x in dict1 if x in dict2}

file1 = open('Results.txt', 'w')
for key,value in comparison.iteritems():
    print >> file1, ('%s: %s' % (key,value)) 
file1.close()

Edit: example编辑:示例

The values stored in each dictionary are timestamps, so I want my final results to look like:每个字典中存储的值是时间戳,所以我希望我的最终结果如下所示:

12:30-11:30 = 1:00 

You can make a tuple of dict1[x] and dict2[x] the key of the dict instead, and unpack accordingly when iterating over the dict items:您可以将dict1[x]dict2[x]元组dict1[x] dict 的键,并在迭代 dict 项时相应地解包:

comparison = {(dict1[x], dict2[x]): dict1[x] - dict2[x] for x in dict1 if x in dict2}

file1 = open('Results.txt', 'w')
for (time1, time2), value in comparison.iteritems():
    print >> file1, ('%s-%s: %s' % (time1, time2, value)) 
file1.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM