⊗pyPmDcKG 101 of 208 menu

Getting All Keys from a Dictionary in Python

To get all keys from a dictionary, use the keys method. Its parameter is empty. The method returns a special object dict_keys.

Let us have the following dictionary:

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

Let's output all the keys from it:

res = dct.keys() print(res) # dict_keys(['a', 'b', 'c'])

To make it easier to work with the dict_keys object, you can convert it to a list. This is done using the list function:

res = list(dct.keys()) print(res) # ['a', 'b', 'c']

Given a dictionary:

dct = { 'x': 1, 'y': 2, 'z': 3 }

Get his keys.

Given a dictionary:

dct = { 1: 'x', 2: 'y', 3: 'z', 4: 'w' }

Get his keys.

Given a dictionary:

dct = { 'x': 1, 'y': 2, 'z': 3 }

Get a list of keys for this dictionary.

Given a dictionary:

dct = { 2: 'ab', 4: 'cd', 6: 'ef' }

Get the product of all keys in the given dictionary.

Given a dictionary:

dct = { 1: 'x', 2: 'y', 3: 'z', 4: 'w' }

Get the list of keys of this dictionary as follows:

[4, 3, 2, 1]
byenru