One Way to Query Wolfram Alpha from Python

You just need to update the \_xmlparser method with the following

def _xmlparser(self, xml):
     data_dics = {}
     tree = etree.fromstring(xml)
     #retrieving every tag with label 'plaintext'
     for e in tree.findall('pod'):
         for item in [ef for ef in list(e) if ef.tag=='subpod']:
             for it in [i for i in list(item) if i.tag=='plaintext']:
                 if it.tag=='plaintext':
                     mykey = e.get('title')
                     if mykey not in data_dics.keys():
                          data_dics[mykey] = [it.text]
                     else:
                         prev = data_dics[mykey]
                         data_dics[mykey] = prev + [it.text]
    return data_dics

Thanks for the test query. There was a bug in the original code because the dict object in python only use the latest value for a given key, say

a["key1"] =3
a["key2"] =4
# a is {"key1":3 , "key2":4}

if assign the “key1” again with 6, you should have

a["key1"] =6 
# a is updated to {"key1":6 , "key2":4}

for multiple value of a given key, we need to use a list value instead. After update and you should be able to get all result:

2 Likes