Python len 函数不适用于字典

2 投票
1 回答
1049 浏览
提问于 2025-04-18 01:41

我有这段代码:

ab = {  'Swaroop'   :   'swaroop@swaroopch.com',
            'Larry'        :    'larry@wall.org',
            'Matsumoto' :   'matz@ruby-lang.org',
            'Spammer'   :   'spammer@hotmail.com'
        }

print "Swaroop's address is", ab['Swaroop']

del ab['Spammer']

print '\nThere are {} contacts in the address-book\n'.format(len(ab))

for name, address in ab.items():
    print 'Contact {} at {}'.format(name, address)

ab['Guido'] = 'guido@python.org'

if 'Guido' in ab:
    print "\nGuido's address is", ab['Guido']

然后在图形界面上我遇到了这个错误:

Traceback (most recent call last):
  File "E:/Python26/cook.py", line 11, in <module>
    print '\nThere are {} contacts in the address-book\n'.format(len(ab))
ValueError: zero length field name in format

为什么会出现这个问题,虽然len(ab) = 3?

我该如何在格式中使用零长度字段名呢?

1 个回答

3

在Python 2.6中,你需要明确指定数据对应的索引,像这样

print '\nThere are {0} contacts in the address-book\n'.format(len(ab))

撰写回答