This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: collections.defaultdict gives KeyError with format()
Type: behavior Stage: resolved
Components: Library (Lib) Versions: Python 2.6
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: benjamin.peterson, eric.smith, ezio.melotti, jednaszewski
Priority: normal Keywords:

Created on 2010-03-13 22:11 by jednaszewski, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (5)
msg101025 - (view) Author: Greg Jednaszewski (jednaszewski) Date: 2010-03-13 22:11
Found on 2.6.2 and 2.6.4:

I expect that printing an uninitialized variable from a defaultdict should work.  In fact it does with old-style string formatting.  However, when you try to do it with new-style string formatting, it raises a KeyError.

>>> import collections
>>> d = collections.defaultdict(int)
>>> "{foo}".format(d)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'foo'
>>> "%(foo)d" % d
'0'
msg101030 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2010-03-13 23:10
str.format() does not take a mapping object. You want:

>>> "{0[foo]}".format(d)
'0'
msg101031 - (view) Author: Greg Jednaszewski (jednaszewski) Date: 2010-03-13 23:46
Oops, thanks.  I should have known that.  However, should this work?  This is what initially led me to file this ticket.  My initial example was a bad one.

>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> d['bar'] += 1
>>> "{bar}".format(**d)
'1'
>>> "{foo}".format(**d)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'foo'
msg101032 - (view) Author: Benjamin Peterson (benjamin.peterson) * (Python committer) Date: 2010-03-13 23:47
No, because that's not the behavior of keyword arguments.
msg101038 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2010-03-14 02:26
See also issue 6081.
History
Date User Action Args
2022-04-11 14:56:58adminsetgithub: 52381
2010-03-14 02:26:27eric.smithsetmessages: + msg101038
2010-03-13 23:47:32benjamin.petersonsetnosy: + benjamin.peterson
messages: + msg101032
2010-03-13 23:46:19jednaszewskisetmessages: + msg101031
2010-03-13 23:10:45eric.smithsetstatus: open -> closed
resolution: not a bug
messages: + msg101030

stage: test needed -> resolved
2010-03-13 22:12:44ezio.melottisetpriority: normal
nosy: + eric.smith, ezio.melotti

stage: test needed
2010-03-13 22:11:07jednaszewskicreate