[英]Python printing a key once from a dictionary within a function
I want to print a key once from a dictionary and I'm trying to have my output look like this. 我想从字典中打印一次密钥,并且试图使输出看起来像这样。 There are two keys, Instructors and Students.
有两个键,教师和学生。 I don't want to print 'Students' for every item in the list, just once like this output.
我不想为列表中的每个项目打印“学生”,就像这样输出一次。 I'm also trying to make the function generic.
我还试图使该函数通用。 Here's the output.
这是输出。
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
users = {
'Students': [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
],
'Instructors': [
{'first_name' : 'Michael', 'last_name' : 'Choi'},
{'first_name' : 'Martin', 'last_name' : 'Puryear'}
]
}
def school(a):
if a == users['Students']:
room = "Students"
else:
room = "Instructors"
list_number = 1
num = 0
for i in a:
fullname = i ['first_name'] + " " + i['last_name']
while list_number <= (len(a)):
num +=1
break
letter_count = len(fullname) - fullname.count(" ")
print room
print num, "-", fullname,"-", letter_count
school(users['Students'])
school(users['Instructors'])
Here's your initial data: 这是您的初始数据:
users = {
'Students': [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
],
'Instructors': [
{'first_name' : 'Michael', 'last_name' : 'Choi'},
{'first_name' : 'Martin', 'last_name' : 'Puryear'}
]
}
We can loop through each item only once and do everything outside of a dedicate function. 我们只能遍历每个项目一次,并在专用功能之外执行所有操作。 (Though you may want to put everything below here into a function and pass
users
into it.) (尽管您可能希望将下面的所有内容放入函数中,并将
users
传递给该函数。)
# Loop through the entire structure
for key, names in users.items():
# Key is either "Students" or "Instructors"
# Names is the list of name dicts
print(key)
# Use enumerate to get an iteration (starting at 0)
# as well as the actual name dict from the names
for iteration, name in enumerate(names):
first_name = name.get('first_name', '')
last_name = name.get('last_name', '')
# Print using placeholders
print("{0} - {1} {2} - {3}".format(
iteration + 1, # iteration starts at 0
first_name.upper(),
last_name.upper(),
len(first_name) + len(last_name)
))
Note that Python dictionaries aren't ordered, so you may get Instructors
first and then Students
, and the order for each student isn't guaranteed either. 需要注意的是Python字典是没有顺序的,所以你可能会得到
Instructors
先Students
,并为每个学生的顺序也不保证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.