Python:如何以递归方式将哈希哈希的所有值存储到字符串中?

时间:2014-09-04 10:42:44

标签: python string dictionary

我有一个数据结构:哈希哈希

{u'english': {u'fluent': u'7', u'good': u'UK'}, u'id': u'1002', u'zone': u'HongKong', u'latin': {u'verbose': u'1023', u'name': u'haro haro'}, u'humble': {u'minor': u'37', u'social': u'123.1231.23', u'milk': u'dailo'}}

如何以递归方式将此数据结构的所有值存储到单个字符串中? 我尝试了以下但它失败了,字符串最后没有任何内容。

stringofvalues = ''
     def printdict(dd,stringofvalues):
         if isinstance(dd, list):                                                                                                            
             for i in np.arange(len(dd)):
                 printdict(dd[i],stringofvalues)
         elif isinstance(dd, dict):
             for key, value in dd.items():
                 printdict(value,stringofvalues)
         else:
             stringofvalues = dd + str(stringofvalues)
             return stringofvalues

1 个答案:

答案 0 :(得分:1)

您可以简单地递归调用所有可能值的函数并加入值,如此

def rec(currentObject):
    if isinstance(currentObject, list):
        return "".join([rec(item) for item in currentObject])
    elif isinstance(currentObject, dict):
        return "".join([rec(item) for item in currentObject.values()])
    elif isinstance(currentObject, str) or isinstance(currentObject, unicode):
        return currentObject
    else:
        raise TypeError("Unexpected type : {}".format(type(currentObject)))

输入的输出是

dailo37123.1231.231023haro haro1002HongKong7UK

您可以使用默认函数参数并使用分隔符

进行优化
def rec(currentObject, joiner=", ".join):
    if isinstance(currentObject, list):
        return joiner([rec(item) for item in currentObject])
    elif isinstance(currentObject, dict):
        return joiner([rec(item) for item in currentObject.values()])
    elif isinstance(currentObject, str) or isinstance(currentObject, unicode):
        return currentObject
    else:
        raise TypeError("Unexpected type : {}".format(type(currentObject)))

输出变为

dailo, 37, 123.1231.23, 1023, haro haro, 1002, HongKong, 7, UK