**已关闭。**此问题为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
1条答案
按热度按时间bakd9h0s1#
.keys()
is aset
-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
(withiter
) and advance it once (withnext
):Your second attempt was foiled by mistakes in where you performed the conversion to
list
, and should have been: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-OO(n)
work), wherenext(iter(thedict))
isO(1)
.