仅选择为元组的字典键? - python

我有一本包含字符串和2元组键的字典。我想将所有2元组键从(x,y)转换为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)

但是我无法避免非元组键的功能。因为它不能避免非元组键,所以该函数修复了两个元组键,但弄乱了非元组键:

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}}}

python大神给出的解决方案

':'.join(k)更改为k if hasattr(k, 'isalpha') else ':'.join(k)。如果它具有属性isalpha,这将使用未更改的对象,这意味着它可能是字符串,否则将其与冒号连接起来。或者,(感谢@Padraic),您可以使用':'.join(k) if isinstance(k, tuple) else k