0

Essentially, I want to store the following XML input into a dictionary.

Extract of input (variable xml_tree)

<listingContentIndexEntry>
    <active>true</active>
    <lastUpdatedDate>2015-05-05</lastUpdatedDate>
    <listingHomeAwayId>/listings/0000/2671f21e-16a7-45c9-a6b7-d94ca801db24</listingHomeAwayId>
    <listingUrl>http://www.a.url</listingUrl>
</listingContentIndexEntry>
<listingContentIndexEntry>
    <active>true</active>
    <lastUpdatedDate>2015-05-05</lastUpdatedDate>
    <listingHomeAwayId>/listings/0000/849302c1-8734-4540-8169-57d71a309dc8</listingHomeAwayId>
    <listingUrl>http://www.a.url</listingUrl>
</listingContentIndexEntry>
<listingContentIndexEntry>
    <active>true</active>
    <lastUpdatedDate>2015-05-05</lastUpdatedDate>
    <listingHomeAwayId>/listings/0000/7fbfa33c-3371-4850-9c21-6a7685dd0ae1</listingHomeAwayId>
    <listingUrl>http://www.a.url</listingUrl>
</listingContentIndexEntry>
<listingContentIndexEntry>
    <active>false</active>
    <lastUpdatedDate>2015-05-05</lastUpdatedDate>
    <listingHomeAwayId>/listings/0000/336b4e46-e710-49a0-a192-ab66e320fe89</listingHomeAwayId>
    <listingUrl>http://www.a.url</listingUrl>
</listingContentIndexEntry>
<listingContentIndexEntry>
.........

My code so far is

xml_tree = ET.fromstring(xml)

#parse xml
for listingContentIndexEntry in xml_tree.iter('listingContentIndexEntry'):
    active = listingContentIndexEntry.find('active').text
    lastUpdatedDate = listingContentIndexEntry.find('lastUpdatedDate').text
    listingId = listingContentIndexEntry.find('listingId').text
    listingUrl = listingContentIndexEntry.find('listingUrl').text


    data = {'listingId':listingId,'active': active,'lastupdateDate': lastUpdatedDate}
    id_dict.update(data)

The data is being read in from the XML correctly (I have printed to screen) but when I print the dictionary, it is only showing one entry when there should be several hundred.

{'lastupdateDate': '2015-06-23', 'listingId': '/listings/0000/c5666884-c74f-4b89-831a-e285720e611c', 'active': 'false'}

How can I add mutiple entries to the dictionary?

Franco
  • 2,846
  • 7
  • 35
  • 54

1 Answers1

1

dict.update method just adds the new elements of dictionary to previous dict, and also updates already set values if same key is encountered in old dict.

dict1 = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female', 'Age':19 }

dict1.update(dict2)
print "Value : %s" %  dict1

Output is :

Value : {'Age': 19, 'Name': 'Zara', 'Sex': 'female'}

You see here the old age is replaced by new age. Similarly in your code new keys are not being set, always previous set keys are being updated. If you would like to get all results make change id_dict to id_list a list and use id_list.append(data) insted.

shaktimaan
  • 1,769
  • 13
  • 14
  • Thank you, I did this using the info in this answer http://stackoverflow.com/a/23826330/545966 – Franco Jun 25 '15 at 02:02