Anthony
Anthony

Reputation: 56

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'])

Upvotes: 0

Views: 147

Answers (1)

Scovetta
Scovetta

Reputation: 3152

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.)

# 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.

Upvotes: 1

Related Questions