计算一个值在字典中出现多少次? (PYTHON 3)

时间:2019-02-20 00:31:11

标签: python database list loops dictionary

假设我有一个这样的名字列表:names = ['James','Bruce','John']

和这样的字典:

                dict= { 
                     'James':{ 'Job' :'Engineer'},          
                       'Bruce':{'Job' : 'Engineer'},
                        'John':{'Job' :'Doctor'}
                         }

我想创建一个字典,计算在字典中出现“医生”或“工程师”的次数,因此输出将类似于:count = {'Doctor':1, 'Engineer':2}.

我的解决方案是创建一个作业列表,然后计算该作业在列表中出现的次数,如下所示:

job_list=[]
count ={}
for k in names:
      job_list.append(dict[k]['Job'] #( so i can have a list like this:
                           #job_list =  ['Engineer','Engineer','Doctor'])
for i in job_list:
    count[i] = 0 
for i in job_list:
    count[i] += 1

有更快的方法吗?

2 个答案:

答案 0 :(得分:0)

您可以在集合库中使用Counter方法来在一天内实现:

from collections import Counter
Counter([dict[person]['Job'] for person in dict])

答案 1 :(得分:0)

如果您不想导入任何内容,则可以通过仅一次遍历字典来改进代码。我叫字典d

job_counts = {}
for k in names:
    job = d[k]['Job']
    if job in job_counts:
        job_counts[job] += 1
    else:
        job_counts[job] = 1

print(job_counts)