mynameisJEFF
mynameisJEFF

Reputation: 4239

Python:How to recursively store all the value of hash of hash into a string ?

I have a data structure: hash of hash

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

How can I recursively store all the values of this data structure into a single string ? I tried the following but it failed miserably and the string contains nothing at the end.

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

Upvotes: 0

Views: 50

Answers (1)

thefourtheye
thefourtheye

Reputation: 239553

You can simply recursively call the function for all the possible values and join the values, like this

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

And the output for your input is

dailo37123.1231.231023haro haro1002HongKong7UK

You can optimize it a little bit, with the default function argument and joining with a delimiter

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

And the output becomes

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

Upvotes: 1

Related Questions