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

Python函数中实现字典键仅打印一次及通用函数构建需求

Got it, let's sort this out for you. You've got a dictionary with keys like "Instructors" and "Students"—each mapping to a list of entries—and you don't want the key name repeated for every single entry. Instead, you want each key printed once, followed by all its numbered entries in that clean format you specified.

Here's a generalized Python function that works for any similar dictionary (not just these two keys):

def print_grouped_entries(data_dict):
    # Iterate over each group (key) and its associated entries
    for group_name, entries in data_dict.items():
        # Print the group name once at the top of its section
        print(group_name)
        # Number each entry starting from 1
        for idx, entry in enumerate(entries, start=1):
            # Unpack the entry (adjust this if your entries have a different structure)
            name, score = entry
            print(f"  {idx} - {name} - {score}")

# Example usage with your sample data
class_data = {
    'Students': [
        ('MICHAEL JORDAN', 13),
        ('JOHN ROSALES', 11),
        ('MARK GUILLEN', 11),
        ('KB TONEL', 7)
    ],
    'Instructors': [
        ('MICHAEL CHOI', 11),
        ('MARTIN PURYEAR', 13)
    ]
}

print_grouped_entries(class_data)

When you run this, you'll get exactly the output you're looking for:

Students
1 - MICHAEL JORDAN - 13
2 - JOHN ROSALES - 11
3 - MARK GUILLEN - 11
4 - KB TONEL - 7
Instructors
1 - MICHAEL CHOI - 11
2 - MARTIN PURYEAR - 13

Quick breakdown of how this works:

  • The function is flexible: it works with any number of groups (keys) in your dictionary—add a "TAs" key later, and it’ll print that section correctly too.
  • enumerate(entries, start=1) handles automatic numbering starting at 1, so you don’t have to track the count manually.
  • The f-string formats each entry to match your requested style. If your entries have more data points (like a student ID), just adjust the unpacking and formatting line to include them.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:34:17