I have a dictionary with both string and 2-tuple keys. I want to convert all the 2-tuple keys from (x,y) to strings that are x:y. Here is my 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, this is the dictionary output I want:
{'category1:category2':
{'numeric_float1':
{'Green:Car': 0.5137635456103902,
'Red:Plane': 0.42304110216698415,
'Yellow:Boat': 0.5679229894797324}}}
I have altered code from a previous SO answer to create a recursive function that changes all the 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)) for k, v in dictionary.items())
convert_keys_to_string(data)
However I cannot get the function to avoid non-tuple keys. Because it does not avoid non-tuple keys, the function fixes the 2-tuple keys but messes up the 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}}}