The Python Oracle

Accessing dict_keys element by index in Python3

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC L Beethoven - Piano Sonata No 8 in C

--

Chapters
00:00 Question
00:36 Accepted answer (Score 270)
01:07 Answer 2 (Score 82)
01:53 Answer 3 (Score 12)
02:15 Answer 4 (Score 8)
02:33 Thank you

--

Full question
https://stackoverflow.com/questions/1855...

Accepted answer links:
[dictionary view object]: http://docs.python.org/3/library/stdtype...

Answer 2 links:
[Python 3.6]: https://www.google.nl/search?clien

Answer 3 links:
[detailed answer]: https://stackoverflow.com/questions/1622...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #dictionary #python3x #key

#avk47



ACCEPTED ANSWER

Score 297


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'



ANSWER 2

Score 89


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




ANSWER 3

Score 17


Python 3

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




ANSWER 4

Score 9


I wanted "key" & "value" pair of a first dictionary item. I used the following code.

 key, val = next(iter(my_dict.items()))