Six ways to get keys from the dictionary in Python

Renesh Bedre    1 minute read

In this article, you will learn how to access the keys of the dictionaries using keys(), items(), list(), and unpacking methods

Create a random dictionary using dict() constructor,

# Python 3.10
x = dict(Texas=1, Florida=2, Arizona=3)
x
# output
{'Texas': 1, 'Florida': 2, 'Arizona': 3}

Get keys using keys() method

Get all keys from the dictionary as a list,

The syntax of dictionary key method: dict.keys(). The keys() method return a copy of all keys as a list.

x.keys()
# output
dict_keys(['Texas', 'Florida', 'Arizona'])

# convert dict_keys object into list
list(x.keys())
# output
['Texas', 'Florida', 'Arizona']

Get keys using for loop

You can also use for loop to iterate over the keys and access them one by one from the dictionary,

for k in x:
  print(k)
# output
Texas
Florida
Arizona

Get keys and values using items() method

You can access the keys and values of the dictionary while looping using the items() method

for k, v in x.items():
  print(k, v)
# output
Texas 1
Florida 2
Arizona 3

Get keys using list

The keys from the dictionary can also be obtained using the list() method,

list(x)
# output
['Texas', 'Florida', 'Arizona']

Get keys from unpacking dictionary

The keys from the dictionary can also be obtained by unpacking the dictionary,

a, b, c = x
a, b, c
# output
('Texas', 'Florida', 'Arizona')

Get keys using * iterable unpacking operator

* iterable unpacking operator (supported in Python 3.5 or later) allows unpacking of dictionary,

[*x]
# output
['Texas', 'Florida', 'Arizona']

Enhance your skills with courses on Python and pandas

References

This work is licensed under a Creative Commons Attribution 4.0 International License

Some of the links on this page may be affiliate links, which means we may get an affiliate commission on a valid purchase. The retailer will pay the commission at no additional cost to you.

Tags:

Updated: