TypeError: 'dict_keys' object is not subscriptable

Question:

I have this code that errors out in python3:

self.instance_id = get_instance_metadata(data='meta-data/instance-id').keys()[0]

TypeError: 'dict_keys' object is not subscriptable

I changed my code and I get different error (I guess I need more experience):

self.instance_id = get_instance_metadata(list(data='meta-data/instance-id').keys())[0]

TypeError: list() takes no keyword arguments
Asked By: netrangermike

||

Answers:

.keys() is a set-like view, not a sequence, and you can only index sequences.

If you just want the first key, you can manually create an iterator for the dict (with iter) and advance it once (with next):

self.instance_id = next(iter(get_instance_metadata(data='meta-data/instance-id')))

Your second attempt was foiled by mistakes in where you performed the conversion to list, and should have been:

self.instance_id = list(get_instance_metadata(data='meta-data/instance-id').keys())[0]  # The .keys() is unnecessary, but mostly harmless

but it would be less efficient than the solution I suggest, as your solution would have to make a shallow copy of the entire set of keys as a list just to get the first element (big-O O(n) work), where next(iter(thedict)) is O(1).

Answered By: ShadowRanger
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.