python - 在下面的代码示例中,如何计算Python中输出的每个字典值?

标签 python dictionary

我正在学习在 Python (2.7) 中使用列表、元组和字典,以及将字典转换为列表并引用它们,但在理解如何将计数添加到特定值时遇到一些困难我正在从字典中检索。

我从以下代码开始:

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

我当前的输出如下:

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

但是,我想为每个参与者或领导者添加计数,因此输出将改为:

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

采用这种格式:

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

我确实读到Python中的字典是无序的,不能在索引中引用,但是有没有一种简单的方法来设置计数器或以我没有看到的方式对每个输出进行计数?

非常感谢您提供的任何见解!

最佳答案

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

应该可以了。阅读有关枚举的更多信息 here

编辑:正如评论中所指出的,您也可以执行enumerate(data, start=1)。在这种情况下,您不需要 count + 1:

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

关于python - 在下面的代码示例中,如何计算Python中输出的每个字典值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38804469/

相关文章:

python - 帮助我了解 python 的日志记录模块及其处理程序

python - tensorflow 错误 : unsupported callable

python - 将 python 日期时间转换为 oracle 数字

swift - Swift 词典中的 underestimatedCount

python - 如何删除 'NoneType' 的字典项?

python - 为字典中的一个键附加多个值

Python 资源模块不起作用

python - 将字符串列表转换为 `IntFlag`

c++ - 它无法将 C++ 映射结构编译为 map<A, pair<B, C>>

ios - 将来自 JSON 字典字典的 http 请求中的数据转换为 Swift 中的一个字典数组