python - Only select dictionary keys that are tuples? -


i have dictionary both string , 2-tuple keys. want convert 2-tuple keys (x,y) strings x:y. here data:

in [4]:  data = {('category1', 'category2'): {'numeric_float1': {('green', 'car'): 0.51376354561039017,('red', 'plane'): 0.42304110216698415,('yellow', 'boat'): 0.56792298947973241}}} data out[4]: {('category1',   'category2'): {'numeric_float1': {('green', 'car'): 0.5137635456103902,    ('red', 'plane'): 0.42304110216698415,    ('yellow', 'boat'): 0.5679229894797324}}} 

however, dictionary output want:

{'category1:category2':      {'numeric_float1':          {'green:car': 0.5137635456103902,          'red:plane': 0.42304110216698415,          'yellow:boat': 0.5679229894797324}}} 

i have altered code a previous answer create recursive function changes keys.

in [5]:  def convert_keys_to_string(dictionary):     if not isinstance(dictionary, dict):         return dictionary     return dict((':'.join(k), convert_keys_to_string(v)) k, v in dictionary.items())  convert_keys_to_string(data) 

however cannot function avoid non-tuple keys. because not avoid non-tuple keys, function fixes 2-tuple keys messes non-tuple keys:

out[5]: {'category1:category2': {'n:u:m:e:r:i:c:_:f:l:o:a:t:1': {'green:car': 0.5137635456103902,    'red:plane': 0.42304110216698415,    'yellow:boat': 0.5679229894797324}}} 

change ':'.join(k) k if hasattr(k, 'isalpha') else ':'.join(k). use unaltered object if has attribute isalpha, means it's string, or join object colon otherwise. alternatively (thanks, @padraic), can use ':'.join(k) if isinstance(k, tuple) else k.


Comments

Popular posts from this blog

javascript - Bootstrap Popover: iOS Safari strange behaviour -

Magento/PHP - Get phones on all members in a customer group -

session - Logging Out Using PHP -