Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在字典中查找最频繁的键,然后查找最频繁的值_Python - Fatal编程技术网

Python 如何在字典中查找最频繁的键,然后查找最频繁的值

Python 如何在字典中查找最频繁的键,然后查找最频繁的值,python,Python,我有一本字典,其中字符串作为键,字符串作为值。首先,我想在字典中找到最常用的键。第二,我想在字典中找到最常用的值 我从一篇长文本中提取了很多单词作为不同的键,然后用该单词所属的词性对该键进行赋值 但下面是我的字典的一个例子: dicts = {"hello":"hey", "hello":"hi", "hey":"hi", "howdy":"hello", "yo":"hi", "hello":"howdy"} 所以,很明显,我希望我的代码能找到“hello”是最常用的键。“hi”是最常见的值

我有一本字典,其中字符串作为键,字符串作为值。首先,我想在字典中找到最常用的键。第二,我想在字典中找到最常用的值

我从一篇长文本中提取了很多单词作为不同的键,然后用该单词所属的词性对该键进行赋值

但下面是我的字典的一个例子:

dicts = {"hello":"hey", "hello":"hi", "hey":"hi", "howdy":"hello", "yo":"hi", "hello":"howdy"}
所以,很明显,我希望我的代码能找到“hello”是最常用的键。“hi”是最常见的值

我尝试了以下方法来查找最常用的键:

from collections import Counter
c = Counter()
for d in dicts.values():
    c += Counter(d)

print(c.most_common())
但是,它找到了最常见的字母,似乎。。。如何让代码找到最频繁的键,然后再找到最频繁的值

谢谢

字典里没有“最常用键”这样的词。在字典中,每个键都必须是唯一的。至于值,这应该可以正常工作:

from collections import Counter
keys = Counter(dicts.values())
mode = keys.most_common(1)
或者,如果您使用的是python 3.4及更高版本:

from statistics import mode
most_common = mode(dicts.values())

第一:在Python中,一个键只有一个值。如果要存储值列表,请使用“列表” 如果要获得计算频率的所有值,请使用
my_dict.values()
。它将返回字典中所有值的列表。 此循环将计数并将其保存到另一个dict中:

frequency = {}
for value in my_dict.values() :
    if value in frequency :
        frequency[value] = frequency[value] + 1
    else :
        frequency[value] = 1

c=Counter(ordbok.values())
不可能有最频繁的键,因为每个键都是唯一的,初始dict无效-不能有重复的键,如
“hello”:“hey”,“hello”:“hi”
。因此,您根本找不到最常用的密钥