For example, I have:

dict_1 ={'1' : ['1', '1', '2'], '2':['1','2','3']} 

Result:

 ['1','2'] 
  • @jfs Yours is true. Removed comments - tutankhamun

2 answers 2

To get a list of dictionary keys:

 >>> list(dict_1) ['1', '2'] 

Just bypassing the dictionary in Python returns the keys, so for example, to print all the keys:

 print(*dict_1) 

Here is a description of what the asterisk * does in Python .

That is, it is not necessary to create a list in order to look at the keys of the dictionary.

dict.keys() returns a view of the dictionary in Python 3, which supports operations on a set of keys (set):

 >>> dict_1.keys() & {'1', '2', '3'} {'2', '1'} 

In Python 2, the dict.keys() method returned a list of keys. You can use dict.viewkeys() on Python 2 to get Python 3 set-like behavior.

     L = [] for key in sorted(dict_1.keys()): ... L.append(key) L ['1', '2'] 

    so it’s not very difficult ... sorted () is needed (or not ...), since key-value pairs are not ordered in dictionaries.

    • Harder than the next answer) - andreymal
    • rather, longer, I would say, but intuitively, in my opinion. & {'1', '2', '3'} here it is still necessary to somehow explain the brow, the cat. does not know the dictionaries. That's right ... but the first example is a bit unclear - those why list () only bypasses the keys ... well, not intuitively clear ... - dio4