簡體   English   中英

如何將dict_keys轉換為整數

[英]How to convert dict_keys to an integer

我有一本字典,其中的鍵是整數,並且是按順序排列的。 有時,我需要從字典中刪除較舊的條目。 但是,當我嘗試執行此操作時,遇到“ dict_keys”錯誤。

    '<=' not supported between instances of 'dict_keys' and 'int'

當我嘗試將值轉換為int時,被告知不支持該操作。

    int() argument must be a string, a bytes-like object or a number, not 'dict_keys'

我在這里看到回答說要使用列表理解。 但是,由於該詞典中可能有上百萬個條目,因此我希望可以通過某種方式執行轉換,而不必在整個鍵列表上執行轉換。


    import numpy as np

    d = dict()
    for i in range(100):
        d[i] = i+10

    minId = int(np.min(d.keys()))
    while(minId <= 5):
        d.pop(minId)
        minId += 1

您無需將dict_keys轉換為int 無論如何,那不是一件有意義的事情。 您的問題是np.min需要一個序列,而d.keys()的返回值不是一個序列。

要獲取最小的可迭代值,請使用常規Python min而不是np.min 但是,在循環中調用min是一種低效的處理方式。 heapq.nsmallest可能會有所幫助,或者您可以找到比字典更好的數據結構。

您想要一個列表是要使用numpy的:

minId = np.min(list(d))

但實際上,您可以在此處使用內置的min ,它介紹了如何進行迭代,對於dict,無論如何,迭代都在鍵上進行

minId = min(d)

您可以使用OrderedDictpop最早的鍵值對。 使用OrderedDict一個優點是它可以記住第一次插入鍵的順序。 在此代碼中,第一個鍵將始終是OrderedDict d中的最小值。 當您使用popitem(last=False) ,它只是刪除最舊的或第一個鍵值對。

from collections import OrderedDict

d = OrderedDict()
for i in range(100):
    d[i] = i+10
d.popitem(last=False) #removes the earliest key-value pair from the dict
print(d) 

如果要刪除最舊的5個鍵值對,請將這些鍵值對提取到元組列表中,然后再次使用popitem(last=False)從頂部將它們刪除(類比):

a = list(d.items())[:5] #get the first 5 key-value pairs in a list of tuples
for i in a:
    if i in d.items():        
        print("Item {} popped from dictionary.".format(i))
        d.popitem(last=False)

#Output:
Item (0, 10) popped from dictionary.
Item (1, 11) popped from dictionary.
Item (2, 12) popped from dictionary.
Item (3, 13) popped from dictionary.
Item (4, 14) popped from dictionary.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM