如何对字典中的值进行计数,并打印与最大金额相关的键和值 [英] How to count values in dictionary and print the key and value associated with the max amount
问题描述
cinos ['cions','coins','icons','scion ','sonic']
现在我已经创建了一个具有随机字典的字典程序字母作为键和卦语作为值,我想找到具有最大量的卦(值)的字母组(键),并打印出这些值。这是我写的:
从集合导入defaultdict
f = open('dictionary.txt ')
d = defaultdict(list)
f中的行
strip = line.rstrip()
key =.join(sorted(strip))
d [key] .append(strip)
count = 0
d.values()中的值:
如果len(values)> count:
count = len值)
print(values)
这将打印所有分配给count的值,但是我只想打印与count相关的最后一个条目。我尝试了值[-1],但没有工作。
不清楚你的期望
count =。count(values)
尝试将其解释为计算字符串对象引用的名称值
出现在字符串对象,这是一个不可避免的和不成功的结束,因为
值
不是一个字符串对象,而''
也是空的。
I have created an anagram program that takes all words from a file and prints the letters followed by all of the words from the file that can be created using those letters. This is an example of what it prints out:
cinos ['cions', 'coins', 'icons', 'scion', 'sonic']
Now that I have created an anagram program that has a dictionary with the random letters as keys and the anagrams as values, I want to find the group of letters(keys) that has the largest amount of anagrams(values) and print just the values. Here is what I have written:
from collections import defaultdict
f= open('dictionary.txt')
d= defaultdict(list)
for line in f:
strip=line.rstrip()
key = "".join(sorted(strip))
d[key].append(strip)
count=0
for values in d.values():
if len(values)>count:
count=len(values)
print(values)
This prints all of the values ever assigned to count, but I just want to print the last entry associated in count. I tried values[-1], but that didn't work.
It is not clear what you expect
count="".count(values)
to do, but Python is trying to interpret it as "count the number of times the string object referenced by the name values
appears within the string object ''
", which is coming to an inevitable and unsuccessful end as values
isn't a string object and ''
is empty anyway.
这篇关于如何对字典中的值进行计数,并打印与最大金额相关的键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!