Python 如何在多个词典中检索最大数量的项
有多种词典,如下所示Python 如何在多个词典中检索最大数量的项,python,dictionary,Python,Dictionary,有多种词典,如下所示 dicts = {'key': 'a'}, {'key': 'b'}, {'key': 'c'}, {'key': 'a'}, {'key': 'a'}, {'key': 'd'}, {'key': 'a'}, {'key': 'c'}, {'key': 'a'}, {'key': 'a'}, {'key': 'c'
dicts = {'key': 'a'},
{'key': 'b'},
{'key': 'c'},
{'key': 'a'},
{'key': 'a'},
{'key': 'd'},
{'key': 'a'},
{'key': 'c'},
{'key': 'a'},
{'key': 'a'},
{'key': 'c'},
{'key': 'd'},
{'key': 'a'},
{'key': 'a'},
{'key': 'b'},
{'key': 'b'},
{'key': 'd'},
{'key': 'b'},
{'key': 'b'},
{'key': 'd'},
{'key': 'b'},
{'key': 'b'},
{'key': 'c'}
我想做以下工作。1) 排除键值为
a
2) 从
a
中检索最频繁的值。
我认为for语句可以很容易地处理它,但由于字典的数量实际上可能多达数万个,我想知道可以尽快处理的代码。假设
dicts
是一个列表或元组:
from collections import Counter
ans = Counter(dic['key'] for dic in dicts if not dic['key'] == 'a').most_common(1)[0]
无论a
实际上是否是最流行的值,这都将起作用。导致
('b', 7)
假设
dicts
实际上是dicts
的列表:
1/排除键值为“a”的对象
filtered = [d for d in dicts if d["key"] != 'a']
2/从“a”中检索最频繁的值
(我假设您的意思是:应用1.后的最频繁值)
这不是语法上有效的Python-你是说要将dicts
作为一个列表吗?你所有的字典都有相同的键吗?好的,现在,你的问题是什么?你试过什么了吗?当你从一个
中说,你的意思是。。。不包括“a”?
from collections import Counter
c = Counter(d["key"] for d in dicts if d["key"] != 'a')
print c.most_common()[0]