Tanzir Uddin
Tanzir Uddin

Reputation: 61

How to get key of a dictionary in a list or tuple?

A dict like ,

c = {1:'a', 2:'b', 3:'c'}

I need to get the keys in list . I write,

x = [c.key()]

but that don't work. how i can do this ? Can i iterate over key of a dictionary ? If i write , c.key() that needs to return's the keys of dict c . But that doesn't do that . Why ?

Upvotes: 1

Views: 2314

Answers (1)

Moses Koledoye
Moses Koledoye

Reputation: 78556

In python 3, c.keys() returns a dict_keys object, so to be sure you have a list, you should do:

x = list(c.keys())

Casting is necessary in python 3 because dict_keys objects are not subscriptable

In python 2, x = c.keys() will return a list.

Update: By default, dictionaries return their keys when you call an iterator on them or try to loop through them directly, so

x = list(c) # list of keys

t = tuple(c) # tuple of keys

will return a list and tuple of the keys in both python 2 and 3

Upvotes: 4

Related Questions