[Tutor] My first recursive function...
Liam Clarke
cyresse at gmail.com
Thu Jul 28 12:23:04 CEST 2005
Hi all,
Spen too much time coding in VBA, so I'm now paranoid about any code I
write.
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.
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.
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.)
If it's all good, then I'm stoked, as I was writing some very unPythonic
code before this.
(I had one of those moments when you stare at your code, realise it looks
ugly and complicated,
and realise that means you're doing it the wrong way. File > New time, I
call it.)
Thanks for any feedback,
Liam
--
'There is only one basic human right, and that is to do as you damn well
please.
And with it comes the only basic human duty, to take the consequences.'
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050728/fb0e74e5/attachment.htm
More information about the Tutor
mailing list