在 Python 中将列表与字典进行比较
Comparing List to Dictionary in Python
我有清单:
['Dinakar','Indiana','Python','Python'].
这只是举例。
现在我有了字典:
{"p1":("Dinakar":1, "Python":1)}
。请注意没有印第安纳州。
现在我想遍历字典并检查列表中的所有项目是否都在字典中。如果它不存在,我会添加。如果它在那里,我会添加计数。
所以最后看起来像:
{"p1":("Dinakar":1, "Python":2, 'Indiana':1)}
重要的是要注意,我的字典看起来像 :
能否请您举例说明我们如何做到这一点?我是 collections
的新手
使用collections.Counter
.
from collections import Counter
items = ['a', 'b', 'c', 'c', 'b', 'a']
counter = Counter()
counter.update(items)
counter.update(['foo', 'bar', 'baz', 'baz', 'bar'])
print(counter)
打印
Counter({'a': 2, 'c': 2, 'b': 2, 'bar': 2, 'baz': 2, 'foo': 1})
要获得裸字典,只需使用 dict()
:
bare_dict(dict(counter))
print(bare_dict)
打印
{'a': 2, 'c': 2, 'b': 2, 'bar': 2, 'baz': 2, 'foo': 1}
我有清单:
['Dinakar','Indiana','Python','Python'].
这只是举例。
现在我有了字典:
{"p1":("Dinakar":1, "Python":1)}
。请注意没有印第安纳州。
现在我想遍历字典并检查列表中的所有项目是否都在字典中。如果它不存在,我会添加。如果它在那里,我会添加计数。
所以最后看起来像:
{"p1":("Dinakar":1, "Python":2, 'Indiana':1)}
重要的是要注意,我的字典看起来像
能否请您举例说明我们如何做到这一点?我是 collections
的新手使用collections.Counter
.
from collections import Counter
items = ['a', 'b', 'c', 'c', 'b', 'a']
counter = Counter()
counter.update(items)
counter.update(['foo', 'bar', 'baz', 'baz', 'bar'])
print(counter)
打印
Counter({'a': 2, 'c': 2, 'b': 2, 'bar': 2, 'baz': 2, 'foo': 1})
要获得裸字典,只需使用 dict()
:
bare_dict(dict(counter))
print(bare_dict)
打印
{'a': 2, 'c': 2, 'b': 2, 'bar': 2, 'baz': 2, 'foo': 1}