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).
I wanted "key" & "value" pair of a first dictionary item. I used the following code.
key, val = next(iter(my_dict.items()))
mydict = {'a': 'one', 'b': 'two', 'c': 'three'}
mykeys = [*mydict] #list of keys
myvals = [*mydict.values()] #list of values
print(mykeys)
print(myvals)
Output
['a', 'b', 'c']
['one', 'two', 'three']
Also see this detailed answer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With