简体   繁体   中英

Count how many times a value appears in dictionary ? (PYTHON 3)

Suppose i have a list of names like this: names = [ 'James','Bruce','John']

and a dictionary like this:

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

I want to create a dictionary that count how many times 'Doctor' or 'Engineer' appear in the dictionary so the output will be like : count = {'Doctor':1, 'Engineer':2}.

My solution is to create a list of the jobs and then count how many times that job appears in the list so it goes like :

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

is there faster way to do this?

you can use Counter method in collections library to achieve this in one line:

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

If you don't want to import anything then your code can be improved by looping through the dictionary just a single time. I'm calling the dict 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM