Search code examples
pythonxmlxbmc

Print dict items in alphabet order


I'm working on my python script to dict the channels items every time when the items is inserted by using this code:

channels = {}
for elem in tv_elem.getchildren():
    if elem.tag == 'channel':
       channels[elem.attrib['id']] = self.load_channel(elem)
       for channel_key in channels:
           channel = channels[channel_key]
           display_name = channel.get_display_name()
           print display_name

Here is what it print out:

20:58:02 T:6548  NOTICE: BBC One UK EN
20:58:02 T:6548  NOTICE: SVT 1 SE SE
20:58:02 T:6548  NOTICE: National Geographic Channel UK EN
20:58:02 T:6548  NOTICE: NRK1 NO NO
20:58:02 T:6548  NOTICE: Discovery Channel UK EN
20:58:02 T:6548  NOTICE: ARD DE DE
20:58:02 T:6548  NOTICE: DR1 DK DK

Here is the XML file:

<?xml version="1.0" encoding="UTF-8" ?>
<tv generator-info-name="www.timefor.tv/xmltv">
        <channel id="www.timefor.tv/tv/162">
            <display-name lang="de">ARD DE DE</display-name>
        </channel>
        <channel id="www.timefor.tv/tv/1">
            <display-name lang="dk">DR1 DK DK</display-name>
        </channel>
        <channel id="www.timefor.tv/tv/130">
            <display-name lang="no">NRK1 NO NO</display-name>
        </channel>
        <channel id="www.timefor.tv/tv/135">
            <display-name lang="se">SVT 1 SE SE</display-name>
        </channel>
        <channel id="www.timefor.tv/tv/10769">
            <display-name lang="en">BBC One UK EN</display-name>
        </channel>
        <channel id="www.timefor.tv/tv/10214">
            <display-name lang="en">National Geographic Channel UK EN</display-name>
        </channel>
        <channel id="www.timefor.tv/tv/10847">
            <display-name lang="en">Discovery Channel UK EN</display-name>
        </channel></tv>

I want to print them in the same alphabet order as the XML file, what I have print it is not in the same order as the XML file. Do you know how I can print the items in the same alphabet order as the XML file using my code?


Solution

  • Based on what you've explained:

    #Additional import
    from collections import OrderedDict
    channels = OrderedDict()
    for elem in tv_elem.getchildren():
        if elem.tag == 'channel':
           channels[elem.attrib['id']] = self.load_channel(elem)
           for channel_value in channels.items():
               print channel_value.get_display_name()
    

    NOTE: This will give you the same order as you read them from the XML, not alphabetical

    EDIT : Since you're using Python 2.6, a small workaround:

    channels = []
    for elem in tv_elem.getchildren():
        if elem.tag == 'channel':
           channels.append( (elem.attrib['id'], self.load_channel(elem)) )
           for channel_value in channels:
               print channel_value[1].get_display_name()