I'm trying to access a dict_key's element by its index:
test = {'foo': 'bar', 'hello': 'world'}
keys = test.keys() # dict_keys object
keys.index(0)
AttributeError: 'dict_keys' object has no attribute 'index'
I want to get foo
.
same with:
keys[0]
TypeError: 'dict_keys' object does not support indexing
How can I do this?
Call list()
on the dictionary instead:
keys = list(test)
In Python 3, the dict.keys()
method returns a dictionary view object, which acts as a set. Iterating over the dictionary directly also yields keys, so turning a dictionary into a list results in a list of all the keys:
>>> test = {'foo': 'bar', 'hello': 'world'}
>>> list(test)
['foo', 'hello']
>>> list(test)[0]
'foo'
Not a full answer but perhaps a useful hint. If it is really the first item you want*, then
next(iter(q))
is much faster than
list(q)[0]
for large dicts, since the whole thing doesn't have to be stored in memory.
For 10.000.000 items I found it to be almost 40.000 times faster.
*The first item in case of a dict being just a pseudo-random item before Python 3.6 (after that it's ordered in the standard implementation, although it's not advised to rely on it).
Another different approach would be use a pandas Series like this:
import pandas as pd
pd.Series(dict).index.values.tolist()
This might be overkilling and not very fast, but for me is very clear and readable.