Vinay's answer should still work, but for Python 2.7+ and 3.2+ the following is recommended:
parent_map = {c:p for p in tree.iter() for c in p}
getiterator() deprecated in favor of iter() , and it's nice to use the new dict understanding constructor.
Secondly, when creating an XML document, it is possible that the child will have several parents, although this will be deleted after the document is serialized. If that matters, you can try the following:
parent_map = {} for p in tree.iter(): for c in p: if c in parent_map: parent_map[c].append(p)
supergra Nov 21 '13 at 21:31 2013-11-21 21:31
source share