python - change key to lower case for dict or OrderedDict -


following works dictionary, not ordereddict. od seems form infinite loop. can tell me why? if function input dict has return dict, if input ordereddict has return od.

def key_lower(d):     """returns d d or od od keys changed lower case     """     k in d.iterkeys():         v = d.pop(k)         if (type(k) == str) , (not k.islower()):             k = k.lower()         d[k] = v      return d 

it forms infinite loop because of way ordered dictionaries add new members (to end)

since using iterkeys, using generator. when assign d[k] = v adding new key/value end of dictionary. because using generator, continue generate keys continue adding them.

you fix in few ways. 1 create new ordered dict previous.

def key_lower(d):      newdict = ordereddict()     k, v in d.iteritems():         if (isinstance(k, (str, basestring))):             k = k.lower()         newdict[k] = v     return newdict 

the other way not use generator , use keys instead of iterkeys


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -