You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何遍历Python嵌套字典并统计获最多Yes(1)响应的学生

问题描述

场景:每位学生开展Yes(1)/No(0)调查,记录其他学生对自己的响应,需要找出获得最多Yes(1)响应的学生。

已完成操作:从文件生成了嵌套字典,文件输入示例如下:

name1: #(for student 1)
name2, 1
name3, 0
name4, 1
…
name2: #(for student 2)
name1, 0
name3, 0
name4, 0
… 以此类推覆盖所有学生

生成的嵌套字典格式示例:

{'name1': {'name2': 1, 'name3': 0, 'name4': 1}, 'name2': {'name1': 0, 'name3': 0, 'name4': 0}}

遇到的问题:不知道如何遍历嵌套字典的所有键值对,统计哪位学生获得的Yes(1)响应最多。

已尝试的代码:

d = {}

with open("C:\\Users\\Administrator\\python\\yearbook.txt") as f:
    for line in f:
        line = line.strip()
        if line.endswith(':'):
            name = line[:-1]
            d[name] = {}
        elif line:
            innername, value = line.split(',')
            d[name][innername] = int(value)


def nested_dict_pairs_iterator(dict_obj):
    ''' This function accepts a nested dictionary as argument
        and iterate over all values of nested dictionaries
    '''
    # Iterate over all key-value pairs of dict argument
    for key, value in dict_obj.items():
        # Check if value is dict type
        if isinstance(value, dict):
            # If value is dict then iterate over all its values
            for pair in  nested_dict_pairs_iterator(value):
                yield (key, *pair)
        else:
            # If value is not dict type then yield the value
            yield (key, value)
#Loop through all key-value pairs of a nested dictionary
count = 0
for pair in nested_dict_pairs_iterator(d):
    if(pair[2]==1):
        count+=1
print(count)
解决方案

你当前的代码仅统计了所有Yes的总数,没有按学生分类统计。可以按以下逻辑修改:

  1. 初始化统计字典:创建空字典,存储每个学生的Yes获票数,初始值全为0。
  2. 双层遍历嵌套字典:外层遍历投票者,内层遍历该投票者对其他学生的投票结果。
  3. 累加Yes计数:若投票结果为1,对应被投票学生的计数加1。
  4. 找出获票最多的学生:从统计字典中筛选出值最大的键,支持并列情况。

修改后的完整代码:

d = {}

with open("C:\\Users\\Administrator\\python\\yearbook.txt") as f:
    for line in f:
        line = line.strip()
        if line.endswith(':'):
            name = line[:-1]
            d[name] = {}
        elif line:
            innername, value = line.split(',')
            d[name][innername] = int(value)

# 初始化所有学生的Yes计数为0
yes_counts = {student: 0 for student in d.keys()}

# 遍历投票数据统计Yes数量
for voter, vote_records in d.items():
    for student, response in vote_records.items():
        if response == 1:
            yes_counts[student] += 1

# 找出获最多Yes的学生
max_count = max(yes_counts.values())
top_students = [stu for stu, cnt in yes_counts.items() if cnt == max_count]

# 输出结果
if len(top_students) == 1:
    print(f"获最多Yes响应的学生是:{top_students[0]},共{max_count}个Yes")
else:
    print(f"获最多Yes响应的学生有:{', '.join(top_students)},均为{max_count}个Yes")

关键说明

  • 字典推导式初始化:快速生成包含所有学生的计数字典,避免遗漏任何学生。
  • 双层遍历逻辑:直接对应投票者→被投票者的关系,比递归迭代器更直观,适合初学者理解。
  • 处理并列情况:如果多个学生获票相同且最多,会全部列出,避免只输出一个的疏漏。

内容的提问来源于stack exchange,提问作者Mayank Pandey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 23:31:46