これは、関数が「深く」進んでいないために発生します。たとえば、@Matthew の回答からサンプル dict を取得しましょう。
d = xmltodict.parse("""
<root>
<abc><def>ab</def></abc>
<abc id="a3">efg</abc>
</root>
""")
In [29]: d
Out[29]: {'root': {'abc': [{'def': 'ab'}, {'#text': 'efg', '@id': 'a3'}]}}
関数は、この dict でキーを 1 つだけ見つけます: root
. ただし、次のような方法ですべてのアイテムを再帰的に反復できます。
# What if you use different from dict Mapping implementation
# ...like OrderedDict or defaultdict? So lets check type
# ...of the nested 'dicts' with Mapping interface
from collections import Mapping
def transform(element, strip_chars="#@"):
if isinstance(element, Mapping):
return {key.strip(strip_chars): transform(value)
for key, value
in element.iteritems()}
elif isinstance(element, list):
return [transform(item) for item in element]
else:
return element
In [27]: d1 = transform(d)
In [28]: d, d1
Out[28]:
({'root': {'abc': [{'def': 'ab'}, {'#text': 'efg', '@id': 'a3'}]}},
{'root': {'abc': [{'def': 'ab'}, {'id': 'a3', 'text': 'efg'}]}})