Python v2.3 and dict.fromkeys() suggestion

Jack Diederich jack at performancedrivers.com
Mon Jun 9 18:04:52 CEST 2003


On Mon, Jun 09, 2003 at 04:33:35AM -0700, Mark J wrote:
> I think it's really great that dictionary types now provide a (fast)
> way to add elements from a sequence.
> 
> It seems, however, that this mechanism could be made more general by
> letting fromkeys() be a regular method instead of restricting it to a
> class method/constructor.  This would allow (quickly) adding elements
> from a sequence (perhaps multiple times) *after* the dictionary has
> been created.
> 
> Besides being more useful, I think this would also be less confusing. 
> (What other built-in has such an alternate constructor?)
> 
> Also, once people get used to the idea of being able to add sequence
> elements to dictionaries, they'll want a regular method to do the same
> anyway (better to make the change before release than deal with a
> dict.update_fromkeys() or other naming issue to complement a fromkeys
> constructor).
> 
> One issue, I suppose, would be what to do if an illegal (non-hashable)
> element was encountered half-way through the update.  But Python could
> check that all elements are hashible prior to updating the dictionary
> much faster and less esotericly than a user could.
> 
> If the change were to be made and the method was no longer going to be
> a constructor, then it may be appropriate to rename the function
> "addkeys".

I once proposed something similar[1], but there wasn't any interest.
Here was the suggestion, although I would break it up into seperate
methods in retrospect.  It is much faster than iterating and updating,
but in practice I don't actually do this with huge lists so YAGNI.

# setup
old_dict = {'foo':1, 'bar':1}
l = ['joe', 'jack', 'mary', 'bill', 'geoff', 'dmitri', 'fima', 'boris']

# assigns keys of names in list, with value set to true
old_dict.populate(l)

# assigns keys of names in list, with value being their index in the list
old_dict.populate(l, range(len(l)))

# like the true example, but every value is 'HiMom'
old_dict.populate(l, 'HiMom') 

lastly, you might actually want to assign the same list or tuple as the
value for every key, so we add an override flag that forces lists in the
second argument to be treated like 'HiMom'

# every name has the value of the list range(len(l))
old_dict.populate(l, range(len(l)), 1)


-jack

[1] http://jackdied.com/code/dead.html (my dropped patches and dead code)
    There is a patch against 2.2.1 there and a link to the OP.






More information about the Python-list mailing list