Python dictionary keys() Method -


i trying figure out when dictionary keys() method mandatory. here code.

rawfeats = [(0, 'mouse'), (1, 'black'), (0, 'cat'), (1, 'tabby'), (2, 'mouse')] ohedict = {(0, 'cat'): 1, (1, 'tabby'): 4, (2, 'mouse'): 5} indices = {ohedict[i]:1.0 in rawfeats if in ohedict} indices1 = {ohedict[i]:1.0 in rawfeats if in ohedict.keys()}  print "indices = {0}\nindices1 = {1}".format(indices, indices1) 

the output is:

indices = {1: 1.0, 4: 1.0, 5: 1.0} indices1 = {1: 1.0, 4: 1.0, 5: 1.0} 

i can understand indices1 work because (0, 'cat')is 1 of keys, why indices turn out same result? hint appreciated. btw, large data set, indices's performance way better indices1.

on python2.x, dict.keys (imho) more or less worthless. can iterate on dictionary's keys directly:

for key in d:     ... 

which more efficient iterating on keys:

for key in d.keys():     ... 

which makes separate list, , then iterates on -- doing iteration twice + bunch of memory overhead of having throw-away list, etc, etc.


your use-case doing membership test on keys. it's difference between:

x in some_list  # "x" item in list? 

and

x in some_dict  # "x" key in dictionary? 

membership tests on list objects o(n) on dict o(1). so, every "turn" of loop, you're doing o(n) list construction , o(n) lookup see if item in list instead of simple o(1) hash lookup of key.

it should noted if ever do need list of dictionary's keys, easily1:

list(d) 

fortunately, python3.x has taken steps in correct direction. d.keys() returns set-like object in python3.x. can use efficiently calculate intersection of 2 dictionaries' keys example can useful in situations.

it's worth pointing out set object in python3.x (called dict_keys object) has o(1) membership testing (as expected of looks set), compared o(n) membership test of list.

1this, consequentially, works in python2.x and python3.x it's nice thing remember when you're trying write code compatible either...


Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -