python - 计算字典键中值重复的次数

标签 python dictionary

我有一个根据数据库中的选择创建的字典,我需要的是从该字典生成一个指标

字典

 # create database dictionary with values
 lds_data = {}
 for lds_item in db_result:
 lds_data.update ({lds_item [1]: {'code_client': lds_item [0], 'city': lds_item [2]}})

字典退出:

 u'BRASIL_ALIMEN ': {' code_client ': u'BRA', 'city': u'SAO PAULO '},
 u'BRASIL_CARROS ': {' code_client ': u'BRC', 'city': u'PARANA '}

指标示例:

code_client: BRA appears 1x within dictionary

总结:

我需要计算 KEY = *code_client* 中的值重复了多少次

我尝试按如下方式执行此操作:

 ct = {}
 for key in lds_data:
     ct ['code_client'] = len (lds_data [key] ['code_client'])

最佳答案

使用Collections.Counter:

from collections import Counter

d = {u'BRASIL_ALIMEN ': {' code_client ': u'BRA', 'city': u'SAO PAULO '},
 u'BRASIL_CARROS ': {' code_client ': u'BRC', 'city': u'PARANA '}}

c = Counter(v[' code_client '] for _, v in d.items())

print(c['BRA'])
# 1

如果你打印c,你会看到它有'code_client'每个值的计数。这使得此方法变得灵活,也许将来的某一天您需要计算 'BRC'

关于python - 计算字典键中值重复的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57776344/

相关文章:

python - 如何将字典存储在文件中并读取/写入该文件?

python - django 文件下载问题

python - 加速从 Golang 的 exec packaqe 访问 python 程序

python blaze计算多列的平均值

python - 将包含转义字符的字符串转换为字典

Python 用 'numpy.ndarray' 创建一个字典

python - ipython 和引用计数

python - 针对曝光不足或过度的照片进行 SimpleCV 色彩校正

java - 使用相同的键订购 map

c++ - 使用指向基础抽象类的指针访问子类成员,这不能是 dynamic_cast