Python dict.keys() Method

4/5 - (1 vote)

Summary: You may want to get a list of all the keys stored in a dictionary. In this use case, the dict.keys() method comes in handy. In this article, I will show some examples of the dict.keys() method to, hopefully, give you a better idea of how the method works.

Definition: The Python dictionary built-in dict.keys() method outputs all the keys of a dictionary, in which the keys are ordered by the position they are inserted.

dict.keys() Syntax

Syntax Declaration:

dict.keys()

Parameters:

dict.keys() does not take any parameters

Output:

The dict.keys() method returns a view object type value that displays all the keys in the dictionary, which changes according to the mutation of the dictionaries state.

Basic Example

An example that displays all the keys of a dictionary representing a grocery list:

groceries_dict = {'apples': 6, 'mangos': 3, 'onions': 5,
                  'garlic': 2, 'peaches': 4, 'melons': 3}

print('All the keys in the grocery list: ')
print(groceries_dict.keys())

The output is:

All the keys in the grocery list: 
dict_keys(['apples', 'mangos', 'onions', 'garlic', 'peaches', 'melons'])

dict.keys() on Empty Dictionary

If you apply dict.keys() to an empty dictionary, the returned value is a dict_keys() object with an empty list, i.e., dict_keys([]).

empty_grocery_list = {}
print('grocery list is empty: ')
print(empty_grocery_list.keys())

Output:

grocery list is empty: 
dict_keys([])

Does a dict_keys() Object Update?

The dict.keys() method returns a view on the dictionary keys, not a copy of the keys. If you change the original dictionary, the view will update and the change will be seen by each variable pointing to the dictionary keys view.

Here’s an example:

# Create empty dictionary
empty_grocery_list = {}
keys = empty_grocery_list.keys()

print('grocery list is empty: ')
print(keys)

# Update dictionary keys
empty_grocery_list.update({'bananas': 6})
print('updated groceries list keys: ')
print(keys)

The output shows that the view has updated:

grocery list is empty: 
dict_keys([])
updated groceries list keys: 
dict_keys(['bananas'])

How to Resolve “TypeError: ‘dict_keys’ object is not subscriptable”?

If you try to access a key from the dict_keys() object returned by the dict.keys() method using the square bracket notation [], Python will raise a TypeError: 'dict_keys' object is not subscriptable.

groceries_dict = {'apples': 6, 'mangos': 3, 'onions': 5,
                  'garlic': 2, 'peaches': 4, 'melons': 3}

# A failed attempt of trying to access the 3rd grocery item key:
print('3rd grocery item key: ')
print(groceries_dict.keys()[2])

Output:

Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 5, in <module>
    print('3rd grocery item key: ' + groceries_dict.keys()[2])
TypeError: 'dict_keys' object is not subscriptable

You can resolve this error by first converting the dict_keys() object to a list object using the list() built-in method and then accessing the i-th element using indexing. This works because unlike dict_keys() objects, lists are subscriptable.

Here’s an example:

groceries_dict = {'apples': 6, 'mangos': 3, 'onions': 5,
                  'garlic': 2, 'peaches': 4, 'melons': 3}

# A failed attempt of trying to access the 3rd grocery item key:
print('3rd grocery item key: ')
print(list(groceries_dict.keys())[2])

The output:

3rd grocery item key: 
onions

A less elegant way to resolve this error is to use a simple for loop over the dictionary itself like so:

groceries_dict = {'apples': 6, 'mangos': 3, 'onions': 5,
                  'garlic': 2, 'peaches': 4, 'melons': 3}

# using a for loop to access the 3rd item of the grocery list:
index = 0

for item in groceries_dict:
    if(index == 2):
        print('3rd grocery item key using a for loop:')
        print(item)
    index = index + 1

Output:

3rd grocery item key using a for loop:
onions

Programmer Humor

πŸ‘±β€β™€οΈ Programmer 1: We have a problem
πŸ§”β€β™‚οΈ Programmer 2: Let’s use RegEx!
πŸ‘±β€β™€οΈ Programmer 1: Now we have two problems

… yet – you can easily reduce the two problems to zero as you polish your “RegEx Superpower in Python“. πŸ™‚