如何按照词典中的词典顺序排序?

2024-10-04 11:31:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我这里有代码:

def most_popular_book(book_loans):
    vBL = book_loans.values()
    kBL = book_loans.keys()
    items = book_loans.items()
    print items
    kBL = sorted(kBL, key=str.lower)
    mvBL = max(vBL)
    for key,vaule in items:
        if vaule == mvBL:
            return key

我使用这段代码的目的是获得值最大的键,如果两个键的值相同,则选择按字典顺序排在第一位的键。你知道吗

现在代码的第一部分工作正常了!但是我对第二部分有困难。 我读了一些关于这个主题的代码,但是我还没有找到一个方法使它工作。你知道吗

代码应如何工作的示例:

print most_popular_book({'harry potter':['yossi','adam'], 
'lilo and stich':['yossi', "adam"], 'catch-22':['adam'] })

'harry potter'

(应该是哈利波特) 但我的代码打印出“lilo和stich”

另一个例子:

{'the little prince': ['yossi'], 'harry potter': ['yossi', 'assaf'], 
 'catch-22': ['yossi', 'dana']}

'catch-22'

(此输出工作正常)


Tags: key代码mostitemsprintadambookloans
2条回答

如果你只想要最流行的书,你可以用min

def most_popular_book(books):
    result, _ = min(books.items(), key=lambda x: (-len(x[1]), x[0]))
    return result


print(most_popular_book({'harry potter': ['yossi', 'adam'],
                         'lilo and stich': ['yossi', "adam"], 'catch-22': ['adam']}))
print(most_popular_book({'the little prince': ['yossi'], 'harry potter': ['yossi', 'assaf'],
                         'catch-22': ['yossi', 'dana']}))

输出

harry potter
catch-22

这个想法与@PatrickArtner的答案相同,唯一的区别是排序的是O(nlogn),min是O(n)。不需要对列表排序,只需找到最小值。你知道吗

您可以通过以下方式获得完全排序的列表:

fancy = sorted( book_loans.items(), key = lambda x:(-len(x[1]), x[0]))

拿第一个。你知道吗

它的工作原理是定义一个tuple作为排序标准-tuples按第一个值排序,如果第一个值绘制,则按第二个值排序,以此类推

-len()排序“反转”它(也可以将reverse=True参数指定为排序-任何一个都有效。你知道吗

fancy = sorted( {'harry potter':['yossi','adam'], 'lilo and stich':['yossi', "adam"],
                 'catch-22':['adam'] }.items(), key = lambda x:(-len(x[1]), x[0])) 

print(fancy)
print(fancy[0][0])

输出:

[('harry potter', ['yossi', 'adam']), ('lilo and stich', ['yossi', 'adam']),
 ('catch-22', ['adam'])]

harry potter

相关问题 更多 >