【问题标题】:How to find minimum value in sorted dictionary with repeat elements?如何在具有重复元素的排序字典中找到最小值?
【发布时间】:2019-10-20 15:06:05
【问题描述】:

我有一本字典,其中键作为项目,值作为价格。我必须打印最便宜的商品。 如果输入是dict_1={'mobile1':11000, 'mobile2':11000, 'mobile3':11000} 然后输出 - mobile1: 11000 如果值相同,则打印最先出现的项目。

如果输入是{'mobile1':10000, 'mobile2':9000, 'mobile3':13000} 输出是 - mobile2: 9000

我的代码适用于第二个输入集,但对于值相同的第一个输入列表失败。

dict_1={'mobile1':11000, 'mobile2':11000, 'mobile3':11000}
mobile=list(dict_1.keys())
price=list(dict_1.values())
for key,val in dict_1.items():
    if dict_1[key]==min(price):
        print('{0}: {1}'.format(key, val))

预期输出:

mobile1: 11000

实际结果:

mobile1: 11000
mobile2: 11000
mobile3: 11000

【问题讨论】:

  • 使用编号键通常被认为是不好的做法。如果您有编号序列,请使用列表。
  • @KlausD.:键不是数字。
  • @martineau 但他们是编号
  • @KlausD。这可能只是为了说明目的。我认为重要的一点是键是排序的字符串。
  • 是的,我接受了。非常感谢

标签: python dictionary


【解决方案1】:

您可以为此使用min() 函数。

>>> dict_1={'mobile1':11000, 'mobile2':11000, 'mobile3':11000}
>>> min(dict_1, key=dict_1.get)
'mobile1'
>>> 

【讨论】:

    【解决方案2】:

    你可以试试这个:

    dict_1 = {'mobile1':11000, 'mobile2':11000, 'mobile3':11000}
    ans = sorted(dict_1.keys(), key = lambda x: dict_1[x])[0]
    print(str(ans) + ': ' + str(dict_1[ans]))
    

    【讨论】:

      猜你喜欢
      • 2017-03-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-07
      • 2011-02-22
      • 1970-01-01
      • 1970-01-01
      • 2015-12-04
      • 2015-08-17
      相关资源
      最近更新 更多