0

I have a list port_ids, which are in right order. Based on that I fetch the value from a file and store it in a dictionary. But the stored values in the dictionary are not aligned with the original list. This is my code:

import os
os.chdir('/var/lib/docker/volumes/kolla_logs/_data/openvswitch/')
port_ids=['qvoee855b93-ba', 'qvo9aa3a7d8-64', 'qvo2fc6e482-aa', 'qvo6a27cf40-8f']

def port_numb(text):
    try:
        with open('ovs-vswitchd.log') as f:
            for line in f:
                if line.find(text) != -1:
                    return line[97:100]
    except Exception as ex:
        print('Failed to open file {}'.format(ex))

ovs_port_numb = list(map(port_numb, port_ids))
d = dict(zip(port_ids, ovs_port_numb))
print d

OUTPUT: {'qvoee855b93-ba': '174', 'qvo2fc6e482-aa': '176', 'qvo6a27cf40-8f': '177', 'qvo9aa3a7d8-64': '175'}

I want the keys of the dictionary to be in the same order like in the list (port_ids).

Ignacio Vergara Kausel
  • 5,521
  • 4
  • 31
  • 41
  • 2
    https://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key has some good tips, something along the lines of OrderedDict should do the trick. – sniperd Jun 09 '17 at 14:56
  • 2
    Possible duplicate of [How can I sort a dictionary by key?](https://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key) – pramod Jun 09 '17 at 15:01

1 Answers1

0

In Python below version 3.6, the order of keys in dictionaries is not guaranteed. If you want such behavior you have to use Python 3.6 or OrderedDict from the collections module as well shown in this link as suggested by sniperd

Ignacio Vergara Kausel
  • 5,521
  • 4
  • 31
  • 41
  • Thanks for quick response.Sorry i forgot to mention i am using python2.7 and my whole setup is running on this version. Therefore, i have to use 2.7. Do you think OrderedDict can work in python2.7? – khawar abbasi Jun 09 '17 at 15:01
  • Yes, OrderedDict is available in Python 2.7 https://docs.python.org/2/library/collections.html#collections.OrderedDict – Ignacio Vergara Kausel Jun 09 '17 at 15:02
  • 1
    Even in 3.6 they advise you not to rely on the dictionary order, and if you need an order dictionary you should still be using OrderedDict. – MooingRawr Jun 09 '17 at 15:19
  • My case is little different. I need the dict key to have exactly the same order of list(ports_ids) rather than ascending or alphabetically. – khawar abbasi Jun 09 '17 at 15:19
  • 1
    "An OrderedDict is a dict that remembers the order that keys were first inserted." I don't see how that is not what you need. – Ignacio Vergara Kausel Jun 09 '17 at 15:25