python TypeError:'dict_keys'对象不是可订阅的[已关闭]

dxxyhpgq  于 2022-12-02  发布在  Python
关注(0)|答案(1)|浏览(159)

**已关闭。**此问题为not reproducible or was caused by typos。目前不接受答案。

这个问题是由一个打字错误或一个无法再重现的问题引起的。虽然类似的问题在这里可能是on-topic,但这个问题的解决方式不太可能帮助未来的读者。
10小时前就关门了。
Improve this question
我有一段代码在python3中出错:

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

TypeError: 'dict_keys' object is not subscriptable

我改变了我的代码,我得到不同的错误(我想我需要更多的经验):

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

TypeError: list() takes no keyword arguments
bakd9h0s

bakd9h0s1#

.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) .

相关问题