I have created a order dictionary and could not get the index out of it.
I have gone through the below url but not working.
line_1 = OrderedDict((('A1', "Miyapur"), ('A2', "JNTU College"), ('A3', "KPHB Colony"),
('A4', "Kukatpally"), ('A5', "Balanagar"), ('A6', "Moosapet"),
('A7', "Bharat Nagar"), ('A8', "Erragadda"), ('A9', "ESI Hospital"),
('A10', "S R Nagar"), ('X1', "Ameerpet"), ('A12', "Punjagutta"),
('A13', "Irrum Manzil"), ('A14', "Khairatabad"), ('A15', "Lakdikapul"),
('A16', "('Assembly"), ('A17', "Nampally"), ('A18', "Gandhi Bhavan"),
('A19', "Osmania Medical College"), ('X2', "MG Bus station"), ('A21', "Malakpet"),
('A22', "New Market"), ('A23', "Musarambagh"), ('A24', "Dilsukhnagar"),
('A25', "Chaitanyapuri"), ('A26', "Victoria Memorial"), ('A27', "L B Nagar")))
TypeError: 'odict_values' object does not support indexing
TypeError: 'odict_keys' object does not support indexing
In Python 3, dictionaries (including
OrderedDict) return "view" objects from their
values() methods. Those are iterable, but don't support indexing. The answer you linked appears to have been written for Python 2, where
values() returned lists.
There are a few ways you could make the code work in Python 3. One simple (but perhaps slow) option would be to pass the view object to
list() and then index it:
Another option would be to use
itertools.islice to iterate over the view object to the desired index:
import itertools print(next(itertools.islice(line_1.values(), 1, 2)))
But all of these solutions are pretty ugly. It may be that a dictionary is not the best data structure for you to use in this situation. If your data was in a simple list, it would be trivial to lookup any item by index (but lookup up by key would be harder).