访问嵌套字典和学生数据

2024-04-18 11:18:32 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我尝试过的代码,实际上我在寻找每个关键字典的比较结果,因此每个字典的最大值将类似于“2539:Mark:35”…其他字典也一样,请在这里帮助我解决这个问题

student_data = {2539:{'James':30, 'Mark': 35}, 8214: { 'Michelle': 32,'Mark': 40},7411:{'Travis':28, 'Mark': 45}}

for id,v in student_data.items():
    print(id, '-->', student_data[id][0] + ',', max(student_data[id][1].values()))
    print('Subjects:', student_data[id][2], '\n')

Tags: 代码intravisidfordata字典items
1条回答
网友
1楼 · 发布于 2024-04-18 11:18:32

尽可能多地使用代码

使用find max in dictionary在字典中查找具有最大值的键

代码

student_data = { 2539: { 'James': 30, 'Mark': 35 }, 8214: { 'Michelle': 32,'Mark': 40 }, 7411: { 'Travis': 28, 'Mark': 45 } }

for id,v in student_data.items():       # v is a dictionary
    max_student = max(v, key=v.get)     # student name with max
    print(f'{id}:{max_student}:{v[max_student]}')

输出

2539:Mark:35
8214:Mark:40
7411:Mark:45

扩展为学生数据的输入信息

def get_parameter(prompt, type_input='str'):
  " Used for getting student id, name or score "
  while True:
    param = input(prompt)
    if not param:
      return None # done entering

    if type_input=='int':
      if param.isdigit():
        return int(param)
      else:
        print('Value should be integer')
    elif type_input == 'str':
      if param.isalpha():
        # string so okay
        return param
      else:
        print('Value should be single word string')

# Get student data as list of stuples
# [(id1, name1, score1), (id2, name2, score2), ...]
while True:
    id = get_parameter('Student id (blank line to close entries):', 'int')
    if not id:
        break  # break inputting data on blank line

    name = get_parameter('Student name: ')
    if not name:
      break

    score = get_parameter('Student score: ', 'int')
    if not score:
      break

    data.append((id, name, score))

# Convert list of tuples to student_data dictionary
student_data = {}
for id, name, score in data:
    if not id in student_data:
        student_data[id] = {}  # add dictionary for id
    # Add score and name
    student_data[id][name] = score

# Show results    
for id,v in student_data.items():
    max_student = max(v, key=v.get )
    print(f'{id}:{max_student}:{v[max_student]}')

相关问题 更多 >