首页 > 解决方案 > 如何对列表中的字典值进行排序?

问题描述

我继续进行编码练习,让我返回一个字典,其中键是单词的长度,值是单词本身。这是通过拆分文本来完成的,文本是传递给 get_word_len_dict(text) 函数的参数并计算字符数。然后对长度进行排序并在 print_dict_in_key_order(a_dict) 中输出。

我得到这样的输出:

2 : ['to', 'is']
3 : ['why', 'you', 'say', 'are', 'but', 'the', 'wet']
4 : ['does', 'when', 'four', 'they', 'have']
5 : ['there', 'stars', 'check', 'paint']
7 : ['someone', 'believe', 'billion']

哪个看起来不错,但是如果我想按字母顺序对列表中的值进行排序呢?这意味着以大写字母开头的单词也应该优先考虑。例如。['五月','和']。

理想情况下,我想要这样的输出,其中的值按字母顺序排列:

2 : ['is', 'to']
3 : ['are', 'but', 'say', 'the', 'wet', 'why', 'you']
4 : ['does', 'four', 'have', 'they', 'when']
5 : ['check', 'paint', 'stars', 'there']
7 : ['believe', 'billion', 'someone']

到目前为止,我已经设法在 print_dict_in_key_order(a_dict) 中对键进行了排序,但如果我还想对值进行排序,不知道该怎么做?

def get_word_len_dict(text):
    dictionary = {}
    word_list = text.split()
    for word in word_list:
        letter = len(word)

        dictionary.setdefault(letter,[])

        if word not in dictionary[letter]:
            dictionary[letter].append(word)

    return dictionary

def test_get_word_len_dict():
    text = 'why does someone believe you when you say there are four billion stars but they have to check when you say the paint is wet'
    the_dict = get_word_len_dict(text)
    print_dict_in_key_order(the_dict)


def print_dict_in_key_order(a_dict): 
    all_keys = list(a_dict.keys()) 
    all_keys.sort() 
    for key in all_keys: 
        print(key, ":", a_dict[key]) 

标签: pythonlistdictionaryfor-loop

解决方案


鉴于这个字典

d = {
    2: ['to', 'is'],
    3: ['why', 'you', 'say', 'are', 'but', 'the', 'wet'],
    4: ['does', 'when', 'four', 'they', 'have'],
    5: ['there', 'stars', 'check', 'paint'],
    7: ['someone', 'believe', 'billion'],
    }

您可以像这样对值进行排序:

{k: sorted(v) for k, v in d.items()}

输出(通过pprint):

{2: ['is', 'to'],
 3: ['are', 'but', 'say', 'the', 'wet', 'why', 'you'],
 4: ['does', 'four', 'have', 'they', 'when'],
 5: ['check', 'paint', 'stars', 'there'],
 7: ['believe', 'billion', 'someone']}

虽然如果您只关心在打印时对其进行排序,只需在代码中更改此行:

print(key, ":", a_dict[key])

对此:

print(key, ":", sorted(a_dict[key]))

推荐阅读