[issue1288] dict.fromkeys - Odd logic when passing second dict.fromkeys as value

Raymond Hettinger report at bugs.python.org
Wed Oct 17 00:35:47 CEST 2007


Raymond Hettinger added the comment:

This isn't a bug.  Writing
"dict.fromkeys(xrange(1,48),dict.fromkeys(xrange(1,8),0))" results in
the inner expression being evaluated just once and then passed to the
outer function call as a fully evaluated argument.  As a result, the
*same* dictionary is being used over and over again.

People commonly encounter similar issue when they try to create
initialized list-of-lists with something like s=[[0]*10] which repeats
ten of the *same* lists.  Instead they should write something like: 
s=[[0] for i in range(10)] which creates *distinct* inner lists.

For you application, consider using a defaultdict which can call a
function as needed to create new, distinct values:

  d = defaultdict(lambda: dict.fromkeys(xrange(1,8), 0))

----------
nosy: +rhettinger
resolution:  -> invalid
status: open -> closed

__________________________________
Tracker <report at bugs.python.org>
<http://bugs.python.org/issue1288>
__________________________________


More information about the Python-bugs-list mailing list