-1

I want to get the key from a randomly given dict,

In [1]: d = {"unknown":1}                                                                                                     
In [2]: d.keys()                                                                                                              
Out[2]: dict_keys(['unknown'])
In [3]: k = [k for k in d.keys()][0]                                                                                          
In [4]: k                                                                                                                     
Out[4]: 'unknown'

The solution is cumbersome,

How could get it done in a succinct way?

Alice
  • 1,360
  • 2
  • 13
  • 28

2 Answers2

1

What about list(d.keys()[0]) ?

SpghttCd
  • 10,510
  • 2
  • 20
  • 25
-2

Just use k = d.keys()[0] if the first key has to be fetched, because d.keys() itself returns a list.

Screenshot of Test run

Mudra
  • 36
  • 8