Python 如何将dict values类{}更改为[]并按键对其排序
我有一根绳子Python 如何将dict values类{}更改为[]并按键对其排序,python,class,dictionary,Python,Class,Dictionary,我有一根绳子 my_string="The way you see people is the way you treat them and the Way you treat them is what they become" 我的def应返回以下内容: {2: ['is'], 3: ['and', 'see', 'the', 'way', 'you'], 4: ['them', 'they', 'what'], 5: ['treat'], 6: ['become', 'peopl
my_string="The way you see people is the way you treat them and the Way you treat them is what they become"
我的def应返回以下内容:
{2: ['is'],
3: ['and', 'see', 'the', 'way', 'you'],
4: ['them', 'they', 'what'],
5: ['treat'],
6: ['become', 'people']}
我的解决方案返回:
{3: {'you', 'see', 'way', 'and', 'the'},
6: {'become', 'people'},
2: {'is'},
5: {'treat'},
4: {'what', 'them', 'they'}}
我需要按键对字典进行排序并更改value的类…我的values类是{},但我需要[]
我的解决方案:
def n_letter_dictionary(my_string):
my_string=my_string.lower().split()
sample_dictionary={}
r=[]
for word in my_string:
lw=len(word)
if lw in sample_dictionary:
sample_dictionary[lw].add(word)
else:
sample_dictionary[lw] = {word}
return sample_dictionary
print(n_letter_dictionary("The way you see people is the way you treat them
and the Way you treat them is what they become"))
我该怎么做?任何人都可以帮忙吗?您有一套,因为您在这里创建了一套:
sample_dictionary[lw] = {word}
您需要将其列为一个列表:
sample_dictionary[lw] = [word]
并使用.append()
,而不是.add()
添加更多元素
请注意,您的代码可以通过以下方式简化:
.setdefault()
返回给定键的值;如果缺少该键,它将首先将该键设置为第二个参数中提供的默认值
如果您只想保留唯一的单词,则必须使用额外的循环将集合转换为事实之后的列表:
def n_letter_dictionary(my_string):
sample_dictionary = {}
for word in my_string.lower().split():
sample_dictionary.set_default(len(word), set()).add(word)
return {l: list(v) for l, v in sample_dictionary.items()}
最后一行是词典理解;它使用相同的键构建一个新的字典,每个集值都转换为一个列表。请注意,集合是无序的,因此生成的列表将以任意顺序列出唯一的单词。如果需要保留输入中单词的顺序,则需要将这些单词收集到一个列表中,然后对每个值应用一种技术
字典在其他方面也是无序的,就像集合一样,无法排序。有关解决方法,请参阅
例如,您可以从排序的(键、值)
对生成一个:
from collections import OrderedDict
def n_letter_dictionary(my_string):
sample_dictionary = {}
for word in my_string.lower().split():
sample_dictionary.set_default(len(word), set()).add(word)
return OrderedDict((l, list(v)) for l, v in sorted(sample_dictionary.items()))
python<3.7中默认情况下,dict是无序的。您可以使用OrderedICT。它保留数据插入的顺序,如果插入已排序的数据,它将保持排序
from collections import OrderedDict
unordered_dict = {
3: {'you', 'see', 'way', 'and', 'the'},
6: {'become', 'people'},
2: {'is'},
5: {'treat'},
4: {'what', 'them', 'they'}}
ordered_dict = OrderedDict()
for key in sorted(unordered_dict.keys()):
ordered_dict[key] = unordered_dict[key]
您还可以使用集合中的Counter()来解决此问题。这会让你的生活更轻松
import collections
c = collections.Counter(mystring.lower().split(' '))
for key in sorted([*c]):
print("{0} : {1}".format(key, c[key]))
字典无法排序。它们是非结构化数据容器(至少达到Python 3.6)。将集合
转换为列表
非常简单,这将以正确的顺序返回项目,但我不确定它将如何打印出来。最后还需要创建OrderedDict
,就像返回OrderedDict(排序(sample\u dictionary.items(),key=lambda x:x[0])
不需要调用keys()
来生成一个键的iterable<代码>排序(无序)
就可以了。是的,我忘了那部分。抢手货
import collections
c = collections.Counter(mystring.lower().split(' '))
for key in sorted([*c]):
print("{0} : {1}".format(key, c[key]))