[Tutor] My first recursive function...

Kent Johnson kent37 at tds.net
Thu Jul 28 13:04:18 CEST 2005


Liam Clarke wrote:
> Just playing with my first recursive function, and just wanted your 
> experienced opinions on whether it's likely to blow up in my face,
> as it all seems to work fine out of the gates, and that makes me a 
> little paranoid.
> 
> For a given list -
> 
> x = [ ['tag', 'CYP'],
>         ['level', '1.000'],
>         ['value', '3.286'],
>         ['extra', [ ['country', 'CYP'], ['date', [ ['year', '1431'], 
> ['month', 'april'], ['day', '1'] ] ], ['location', '370'], ['success', 
> 'yes'] ] ] ]
> 
> My data will always be in format [key:info], the question is whether or 
> not value is a list of [key:info]s also. I then want to turn this into
> a nested dictionary.
[key, info] you mean...

> So, the given function...
> 
> def isNested(data):
>     dic = {}
>     for (key, info)  in data:
>         if isinstance(info], list) and isinstance(info[0], list):
>             dic[key] = isNested(info)
>         else:
>             dic[key] = info
>    
>     return dic
> 
> ...seems to work alright, but as I've already run astray of the the 
> isNested(data, dic = {} ) gotcha, I'm just covering my bases here.

Looks good to me other than the name :-) I would call it toDict() or toNestedDict() maybe; IMO a function named isXXX should just return True or False.
 
> Are there any other pitfalls with recursion I need to watch for?
> (I'm also expecting the occasional list that is simply a list of 
> strings, hence the and clause in the isinstance check.)

The biggest pitfall I can think of is that you get into an infinite recursion. This can happen when the recursive call for some reason uses the same arguments as were passed to the caller, or when the exit condition is never met. I think you're fine on both counts here.

Does this mean you gave up on pyparsing Dict?



More information about the Tutor mailing list