timothy-knab timothy-knab - 4 months ago 16
Python Question

How can I count each dictionary value output in Python in the following code example?

I'm learning to play with lists, tuples and dictionaries in Python (2.7), and to convert dictionaries to lists and to reference them, but am experiencing some difficulties in understanding how I might add a count number to specific values that I am retrieving from dictionaries.

I start with this code as follows:

users = {
'Participants': [
{'first_name': 'Jerry', 'last_name' : 'Johnson'},
{'first_name' : 'Blaine', 'last_name' : 'Diamond'},
{'first_name' : 'Ginny', 'last_name' : 'Gelspy'},
{'first_name' : 'LG', 'last_name' : 'Murphy'}
],
'Leaders': [
{'first_name' : 'TJ', 'last_name' : 'Knight'},
{'first_name' : 'Jasper', 'last_name' : 'Red'}
]
}

users_list = users.items() # converts users dict to a list
for key, data in users_list:
print key
for value in data:
print "-", value["first_name"].upper(), value["last_name"].upper(), "-", len(value["first_name"] + value["last_name"])


My current output is as follows:

Participants
- JERRY JOHNSON - 12
- BLAINE DIAMOND - 13
- GINNY GELSPY - 11
- LG MURPHY - 8
Leaders
- TJ KNIGHT - 8
- JASPER RED - 9


However, I'd like to add a count to each participant or leader, so the output would instead read:

Participants
1 - JERRY JOHNSON - 12
2 - BLAINE DIAMOND - 13
3 - GINNY GELSPY - 11
4 - LG MURPHY - 8
Leaders
1 - TJ KNIGHT - 8
2 - JASPER RED - 9


in this format:

<dictionary name>
<count> - <FULL NAME IN CAPS> - <char count in full name no space included>


I did read that dictionaries in python are unordered and cannot be referenced in regards to index, but is there a simple way to setup a counter or to count each output in a way that I'm not seeing?

Thank you so much for any insight provided!

Answer
for key, data in users_list: 
    print key
    for count, value in enumerate(data):
        print (count + 1), "-", value["first_name"].upper(), value["last_name"].upper(), "-", len(value["first_name"] + value["last_name"])

That should do it. Read more about enumerate here

EDIT: As pointed out in the comments, you can also do enumerate(data, start=1) instead. You wouldn't need count + 1 in that case:

for key, data in users_list: 
    print key
    for count, value in enumerate(data, start=1):
        print count, "-", value["first_name"].upper(), value["last_name"].upper(), "-", len(value["first_name"] + value["last_name"])