简体   繁体   English

在 Python 中按升序将值插入字典?

[英]Insert values to a dictionary in an ascending order in Python?

I have aa class that gets key and value and add them to a dictionary.我有一个类,它获取键和值并将它们添加到字典中。 I am trying to insert into the dict while keeping the order of the values in an ascending order.我试图插入字典,同时保持值的升序顺序。 I know that OrderedDict remembers the order that keys were first inserted, but wondering what to use if I want to keep the values of the dict sorted as well.我知道 OrderedDict 会记住第一次插入键的顺序,但想知道如果我想保持 dict 的值排序以及使用什么。 Here is an example:下面是一个例子:

rom collections import OrderedDict
from random import randint


class MyDict():
    def __init__(self):
        self.d=OrderedDict()

    def add(self, key, val):
        self.d[key] = val

    def show(self):
        return self.d

i=1
obj=MyDict()
for _ in range(5):
    obj.add(i, randint(1,50))
    i+=1

print(obj.show())
OrderedDict([(1, 8), (2, 6), (3, 10), (4, 32), (5, 15)])

However, I am looking to get something like this:但是,我希望得到这样的东西:

OrderedDict([(2, 6), (1, 8), (3, 10), (5, 15), (4, 32)])

Since it is apparent from your comments that you only need the dict sorted upon output but not during a series of insertions, you don't actually need to incur the overhead of sorting upon each insertion, but rather you can add sorting to methods where the order matters, which can be done by subclassing OrderedDict and overriding all such methods with ones that would sort the items first.由于从您的评论中可以明显看出,您只需要在输出时对 dict 进行排序,而不需要在一系列插入期间对 dict 进行排序,因此您实际上不需要在每次插入时产生排序的开销,而是可以将排序添加到方法中顺序很重要,这可以通过OrderedDict并用首先对项目进行排序的方法覆盖所有此类方法来完成。

The example below overrides the __repr__ method just so that printing the object would produce your desired output, but you should override all the other relevant methods for completeness:下面的示例覆盖了__repr__方法,以便打印对象会产生您想要的输出,但为了完整性,您应该覆盖所有其他相关方法:

class MyDict(OrderedDict):
    def __sorted(self):
        sorted_items = sorted(super().items(), key=lambda t: t[::-1])
        self.clear()
        self.update(sorted_items)

    def __repr__(self):
        self.__sorted()
        return super().__repr__()

    # do the same to methods __str__, __iter__, items, keys, values, popitem, etc.

Demo: https://replit.com/@blhsing/RudeMurkyIntegrationtesting演示: https : //replit.com/@blhsing/RudeMurkyIntegrationtesting

Since you are looking to sort the dictionary based on the values由于您希望根据值对字典进行排序

>>> from collections import OrderedDict
>>> from random import randint
>>> 
>>> d = OrderedDict()
>>> 
>>> i=1
>>> for _ in range(5):
...     d[i] = randint(1,50)
...     i+=1
... 
>>> 
>>> sorted(d.items(),key=lambda x:(x[1],x[0]))
[(2, 2), (5, 20), (3, 35), (1, 36), (4, 47)]
>>> 

key within sorted can be used in this case to sort based on values在这种情况下,可以使用 sorted 内的key根据值进行排序

I think you should use a set instead.我认为你应该使用 set 代替。 Insert the key value pair in the set and use a custom comparator function to get the order you want.在集合中插入键值对并使用自定义比较器函数来获取您想要的顺序。

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

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