python - Turn dict into list wipes out the values -
short question: why when list(dict()) return keys of dict, not values? cause know (key, value) pairs, matters value, not key. key it's page in book. since don't want page, content of page, giving me page makes no sense @ @ first.
i believe it, somehow, makes sense. please, clarify one.
thanks!
edited: now, since relevant part of (key, value) pair value. why not the iter method of dict returns value?
the reason why occurs because list
accepts iterator, , uses each item if iterator calling iter
on it. since __iter__
method of dict
type returns iterator on it's keys, calling list
on dict
object gives it's keys.
>>> class a(object): def __init__(self,lst): self.lst = lst def __iter__(self): print 'iter on a' return iter(self.lst) >>> = a(range(10)) >>> list(a) iter on [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
in terms of implementation, returning keys faster returning both, , since explicitly include items
method, there doesn't exist reason including values in default __iter__
implementation. implementation of dict timecomplexity data python indicate iterating on keys o(n)
, retrieving values o(1)
, may seem insignificant, until realize iterating , retrieving values given keys o(n)
also. wasteful unless wanted key,value pairs (as opposed keys, or values), it's not default.
if wanted default, this:
class mydict(dict): def __iter__(self): return self.iteritems()
and calling list
on instance of mydict
give key, value pairs.
Comments
Post a Comment