我有一个字典与字符串和2元组键。我想将(x,y)中的所有2元组键转换为x:y的字符串。这里是我的数据:只选择元组的字典键?
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}}}
然而,这是字典输出我想:创建一个递归函数,改变所有的按键
{'category1:category2':
{'numeric_float1':
{'Green:Car': 0.5137635456103902,
'Red:Plane': 0.42304110216698415,
'Yellow:Boat': 0.5679229894797324}}}
我修改代码a previous SO answer。
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)
但是我无法获得避免非元组键的函数。因为它没有避免非元组键,功能修复的2元组密钥,但打乱了非元组键:
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}}}
我想喂鸭类型,但。 – TigerhawkT3
我不遵循,如果hasattr(k,'isalpha')'做了issinstance(k,str)'不会呢? –
我不是在问是否是鸭子,而是在聆听庸医。 :) – TigerhawkT3