简体   繁体   中英

How to pass multiple values into a dictionary

so i have the following code:

    {'stu_name': 'Abel', 'sex': 'male', 'score': 90, 'cls_id': 1},
    {'stu_name': 'Carl', 'sex': 'male', 'score': 80, 'cls_id': 2},
    {'stu_name': 'Cecil', 'sex': 'female', 'score': 60, 'cls_id': 1},
    {'stu_name': 'Elijah', 'sex': 'female', 'score': 70, 'cls_id': 2},
    {'stu_name': 'Dick', 'sex': 'male', 'score': 90, 'cls_id': 3},
    {'stu_name': 'Donald', 'sex': 'male', 'score': 80, 'cls_id': 3},
    {'stu_name': 'Jack', 'sex': 'male', 'score': 80, 'cls_id': 2},
    {'stu_name': 'Laurent', 'sex': 'female', 'score': 90, 'cls_id': 1},
    {'stu_name': 'Rex', 'sex': 'female', 'score': 90, 'cls_id': 1},
    {'stu_name': 'Tom', 'sex': 'male', 'score': 70, 'cls_id': 2},
    {'stu_name': 'Roy', 'sex': 'female', 'score': 90, 'cls_id': 3},
    {'stu_name': 'Steve', 'sex': 'male', 'score': 70, 'cls_id': 1}
]
cls_list = [
    {'id': 1, 'cls_name': 'Class One'},
    {'id': 2, 'cls_name': 'Class Two'},
    {'id': 3, 'cls_name': 'Class Three'},
    {'id': 4, 'cls_name': 'Class Four'}
]

What i want, is to make the program output the class name, followed by the number of people in it, followed by the number of males in it and finally followed by the number of females. What I have so far is this:

lst_empty = {}
for cls in cls_list:
    lst_empty.setdefault(cls['cls_name'], 0)
    for stu in stu_list:
      if stu['cls_id'] == cls['id']:
          lst_empty[cls['cls_name']] +=1
      if stu['sex'] == 'male':

since setdefault can only get me 2 items, I'm kind of stuck on what to do with the if sex = male bit. I guess my main question is how do I pass in the number of males into the empty dictionary. I don't want to drastically change my code, I just want to know what I can do with the code I have right now. Thanks!

I have made lst_empty as a list of dicts. The code is as follows:

stu_list = [{'stu_name': 'Abel', 'sex': 'male', 'score': 90, 'cls_id': 1},
            {'stu_name': 'Carl', 'sex': 'male', 'score': 80, 'cls_id': 2},
            {'stu_name': 'Cecil', 'sex': 'female', 'score': 60, 'cls_id': 1},
            {'stu_name': 'Elijah', 'sex': 'female', 'score': 70, 'cls_id': 2},
            {'stu_name': 'Dick', 'sex': 'male', 'score': 90, 'cls_id': 3},
            {'stu_name': 'Donald', 'sex': 'male', 'score': 80, 'cls_id': 3},
            {'stu_name': 'Jack', 'sex': 'male', 'score': 80, 'cls_id': 2},
            {'stu_name': 'Laurent', 'sex': 'female', 'score': 90, 'cls_id': 1},
            {'stu_name': 'Rex', 'sex': 'female', 'score': 90, 'cls_id': 1},
            {'stu_name': 'Tom', 'sex': 'male', 'score': 70, 'cls_id': 2},
            {'stu_name': 'Roy', 'sex': 'female', 'score': 90, 'cls_id': 3},
            {'stu_name': 'Steve', 'sex': 'male', 'score': 70, 'cls_id': 1}]

cls_list = [{'id': 1, 'cls_name': 'Class One'},
            {'id': 2, 'cls_name': 'Class Two'},
            {'id': 3, 'cls_name': 'Class Three'},
            {'id': 4, 'cls_name': 'Class Four'}]

lst_empty = []
for cls in cls_list:
    dct = {}

    dct.setdefault(cls['cls_name'], 0)
    dct.setdefault('male', 0)
    for stu in stu_list:
        if stu['cls_id'] == cls['id']:
            dct[cls['cls_name']] +=1
            if stu['sex'] == 'male':
                dct["male"] += 1
    dct["female"] = dct[cls["cls_name"]] - dct["male"]

    lst_empty.append(dct)

for i in lst_empty:
    print(i)

The output is:

{'Class One': 5, 'male': 2, 'female': 3}
{'Class Two': 4, 'male': 3, 'female': 1}
{'Class Three': 3, 'male': 2, 'female': 1}
{'Class Four': 0, 'male': 0, 'female': 0}

The easiest, yet not ideal solution is:

for cls in cls_list:
    cls_students = list(filter(lambda s: s['cls_id'] == cls['id'], stu_list))
    cls_males    = list(filter(lambda s: s['sex']    == 'male'   , cls_students))
    cls_females  = list(filter(lambda s: s['sex']    == 'female' , cls_students))
    print(cls['cls_name'])
    print(f"Total students: {len(cls_students)}")
    print(f"Num of males:   {len(cls_males)   }")
    print(f"Num of females: {len(cls_females) }")

But you better consider pandas library with its convenient DataFrame s

Just use dict.get :

dct = {}

for stu in stu_list:
    if stu['cls_id'] == cls['id']:
        dct[cls['cls_name']] = dct.get(cls['cls_name'], 0) + 1
        # will handle both 'male' and 'female' cases
        dct[stu['sex']] = dct.get(stu['sex'], 0) + 1

lst_empty.append(dct)

You could setdefault an empty list or another dictionnary.

lst_empty.setdefault(cls['cls_name'], [0, 0, 0]) 

or

lst_empty.setdefault(cls['cls_name'], {"nb_people" : 0, "nb_male" : 0, "nb_female" : 0})

You can do it this way if you want the result top be stored in a dict:

cls_dict = {}


for cls in cls_list:
    cls_dict[cls['id']]={}
    cls_dict[cls['id']]['id']=cls['id']
    cls_dict[cls['id']]['cls_name']=cls['cls_name']
    cls_dict[cls['id']]['population']=0
    cls_dict[cls['id']]['males']=0
    cls_dict[cls['id']]['females']=0


for stu in stu_list:
    if stu['cls_id'] in cls_dict:
        id = stu['cls_id']
        if stu['sex']=='female':
            cls_dict[id]['females']+=1
            cls_dict[id]['population']+=1
        elif stu['sex']=='male':
            cls_dict[id]['males']+=1
            cls_dict[id]['population']+=1
            

print(cls_dict)

The output will be:

{1: {'id': 1, 'cls_name': 'Class One', 'population': 5, 'males': 2, 'females': 3},
 2: {'id': 2, 'cls_name': 'Class Two', 'population': 4, 'males': 3, 'females': 1},
 3: {'id': 3, 'cls_name': 'Class Three', 'population': 3, 'males': 2, 'females': 1},
 4: {'id': 4, 'cls_name': 'Class Four', 'population': 0, 'males': 0, 'females': 0}}

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