简体   繁体   English

如何将多个值传递到字典中

[英]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.我想要的是将程序 output 命名为 class 名称,然后是其中的人数,然后是其中的男性人数,最后是女性人数。 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.因为 setdefault 只能给我 2 件物品,所以我有点纠结于如何处理 if sex = male 位。 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.我已将lst_empty作为字典列表。 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: output 是:

{'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但是您最好考虑pandas库及其方便的DataFrame s

Just use dict.get :只需使用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.您可以 setdefault 一个空列表或另一个字典。

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: output 将是:

{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}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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