如何在列表中按字典值排序?

3

我在进行一项编码练习,需要返回一个字典,其中键是单词的长度,值是单词本身。这是通过将文本分割为参数传递给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']

这看起来没问题,但如果我想按字母顺序对列表中的值进行排序呢?这意味着以大写字母开头的单词也应该优先考虑。例如:['May','and']。

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

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]) 
3个回答

2

Given this dict

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]))

很抱歉,我应该明确一下,有没有一种方法可以在不删除我的代码中的任何功能的情况下实现这个? - Noneiffy04
@Noneiffy04 好的,就像我写的那样,"如果你只关心在打印时对其进行排序,只需更改此行" ... - wjandrea

2
你需要做的是按长度分组,然后按值排序(因为在词典顺序比较中,大写字母比小写字母“小”),然后从每个组中删除重复项,并将所有内容放入字典理解中。
请注意,与例如pandas中的类似函数不同,itertools.groupby将非连续组视为不同,因此我们需要先按长度排序。
示例:
from itertools import groupby
from pprint import pprint

def solution(sentence):
    sorted_words = sorted(sentence.split(' '), key=len)
    return {length: sorted(set(words)) for length, words in groupby(sorted_words, len)}

sentence =  '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'

pprint(solution(sentence))

输出:

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

请注意,'Why'在其他单词之前是因为它以大写字母开头,并且其余单词按字母顺序排序。
如果要保留函数结构,您可以直接就地对字典中的每个列表进行排序:
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)

    for words in dictionary.values():
        words.sort()

    return dictionary

抱歉,我之前应该明确说明,但是有没有不必删除任何函数就能完成这个任务的方法?此外,我对导入一点也不熟悉。非常抱歉,但我希望我的三个函数保持完整。 - Noneiffy04
1
@Noneiffy04 这很简单,看看我的编辑答案。只需要添加两行代码即可。 - gmds

1
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'],
    }

for i in d:
    d[i].sort()
print(d)

输出

   {
    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']
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接