【问题标题】:operations on dictionary [closed]字典操作[关闭]
【发布时间】:2021-07-12 02:02:02
【问题描述】:

我有两个字典 dict 1dict 2

dict1 是来自机器学习模型的模型分数的原始字典,dict2 是基于某些条件的修改分数。在dict2 中,我基本上是根据某些条件覆盖模型分数,因此任何数量的键都可以将其分数设为 1.0 ,也有可能没有分数被覆盖。所以在那种情况下dict1 = dict 2 我想创建 output_dict,这样如果超过 1 个键的分数被覆盖为 1.0,我想给原始分数更高的分数 1.0。 dict1 和 dict2 的长度是相同的,在下面的例子中我保持它为 4,但在实际工作中它可以是任何东西。

dict1 = {'A':0.78, 'B':0.64, 'C':0.67, 'D':0.56}
dict2 = {'A':0.78, 'B':1.0, 'C':1.0, 'D':0.56}
outout_dict ={'A':0.78,'B':0.64,'C':1.0,'D':0.56} 

例如,在上面的例子中,'B''C' 的分数都是 1.0,但只有 C 的分数在 output_dict 中保持为 1.0,因为它在 dict1 中的概率更高

有没有一种优雅的 Pythonic 方式,我陷入了很多 for 和 if 循环

dict1 = {'A':0.78, 'B':0.64, 'C':0.67, 'D':0.56}
dict2 = {'A':0.78, 'B':1.0, 'C':1.0, 'D':0.56}
keys =[]
for key,value in dict2.items():
    if value == 1.0:
        keys.append(key)
#keys = ['B', 'C']
        
for k,v in dict1:
    if 

【问题讨论】:

  • 你能发布一个你迄今为止尝试过的sn-p吗?
  • ^添加了一些代码sn-ps

标签: python loops sorting dictionary


【解决方案1】:
dict1 = {'A': 0.78, 'B': 0.64, 'C': 0.67, 'D': 0.56}
dict2 = {'A': 0.78, 'B': 1.0, 'C': 1.0, 'D': 0.56}
Lowestchange = [1.00 ,""]
for key in dict1:
   if(dict2[key] - dict1[key] < Lowestchange[0] and dict2[key] != dict1[key] ):
       Lowestchange = [dict2[key] - dict1[key] , key]
if(Lowestchange[1] != ""):
 dict1[Lowestchange[1]] = dict2[Lowestchange[1]]
print(dict1)

【讨论】:

  • 当 dict1 = dict2 时上述失败
  • 是的,那么什么都不会发生,对吧?
  • 是的,在这种情况下它应该返回 dict1,这里它会抛出错误
  • 修复了问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-27
  • 1970-01-01
  • 2019-12-09
  • 2018-08-11
  • 2019-01-29
相关资源
最近更新 更多