i have created order dictionary , not index out of it. have gone through below url not working.
here code , output.
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"))) print(line_1.values()[1]) print(line_1[1]) print(line_1.keys()[1])
all above options not working mentioned in referenced link. guidance highly appreciated. here output each print statement in given order.
typeerror: 'odict_values' object not support indexing
keyerror: 1
typeerror: 'odict_keys' object not support indexing
in python 3, dictionaries (including ordereddict
) return "view" objects keys()
, values()
methods. iterable, don't support indexing. answer linked appears have been written python 2, keys()
, values()
returned lists.
there few ways make code work in python 3. 1 simple (but perhaps slow) option pass view object list()
, index it:
print(list(line_1.values())[1])
another option use itertools.islice
iterate on view object desired index:
import itertools print(next(itertools.islice(line_1.values(), 1, 2)))
but of these solutions pretty ugly. may dictionary not best data structure use in situation. if data in simple list, trivial lookup item index (but lookup key harder).
Comments
Post a Comment