【问题标题】:Compare Two Dictionaries and Print Difference比较两个字典并打印差异
【发布时间】:2019-08-03 06:52:53
【问题描述】:

我已经获取了两个字典的值之间的差异。我目前所拥有的工作,但我想将“dict1 [x] - dict2 [x]”打印到我在结果前面写入的文件中。不仅仅是结果。我怎样才能做到这一点?我需要嵌套循环吗?

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()

编辑:示例

每个字典中存储的值都是时间戳,所以我希望我的最终结果如下所示:

12:30-11:30 = 1:00 

【问题讨论】:

  • 不清楚您所说的I want to print "dict1[x] - dict2[x]" to the file I write to in front of the results 是什么意思。您能否使用示例输入和预期输出更新您的问题?

标签: python python-2.7 for-loop dictionary-comprehension


【解决方案1】:

您可以将 dict1[x]dict2[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()

【讨论】:

  • 是否可以同时包含密钥?例如,key: time1 - time2 = value
猜你喜欢
  • 2019-05-15
  • 1970-01-01
  • 1970-01-01
  • 2015-01-25
  • 2013-06-17
  • 2016-12-24
  • 2013-04-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多