2

I am calling a web API in Python, getting data back in XML, converting the response into a dictionary using xmltodict, but for several elements, sometimes I get a dictionary (single element) and sometimes I get a list (multiple elements) in response.

I first started to use "if isinstance(..., dict):" - that could solve my problem but is not so elegant and requires quite some lines of code in my case. I then found out "force_list" which I think is exactly what I need, but I need to apply it to several elements and I can't find the right syntax - I'm not even sure if that's possible.

The code I am trying to make work:

response = xmltodict.parse(xml, force_list=({'Child'},{'Brother'}))

With force_list={'Child'} only, the code works as expected. With the above code, I do not get any error message but when checking the result with the "type" function, I still have dictionaries where I would expect to get lists. I tried other syntax and got error messages.

Community
  • 1
  • 1
Phileas
  • 41
  • 4
  • I am facing the same situation in a Python program I am writing. I really feel uncomfortable with this non-elegant code. Did you find a way to make it more elegant? – Salva Jul 08 '20 at 23:51

1 Answers1

2

I think I found the right syntax (it seems to be working as I expected):

response = xmltodict.parse(xml, force_list=('Child','Brother'))

Just posting in case anyone would look for the same answer in the future.

Phileas
  • 41
  • 4