Get keys of Dictionary Python | Example code

Use key() method to get keys of Dictionary in Python. It doesn’t take any parameters and returns a view object that displays a list of all the keys.

dict.keys()

Example get keys of Dictionary in Python

Simple example code.

emp = {'name': 'John', 'age': 30, 'salary': 70000}

print(emp.keys())

Output:

Get keys of Dictionary Python

Example get dictionary keys as a list in Python

Python program with a custom function to get dictionary keys as a list.

def get_list(d):
    return d.keys()


# Driver program
dict1 = {1: 'A', 2: 'B', 3: 'C'}
print(get_list(dict1))

Output: dict_keys([1, 2, 3])

Another example gets a pure list of keys from a given dictionary

def get_list(d):
    lst = []
    for key in d.keys():
        lst.append(key)

    return lst


# Driver program
dict1 = {1: 'A', 2: 'B', 3: 'C'}
print(get_list(dict1))

Output: [1, 2, 3]

Do comment if you have any questions or suggestions on this Python dict tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.