Web development and Tech news Blog site. WEBISFREE.com

HOME > python

Print all keys in a python dictionary type

Last Modified : 05 Oct, 2023 / Created : 05 Oct, 2023
86
View Count
Here, we will learn how to print all key information that a dictionary type has in Python.




# Printing All Keys Possessed by Python Dictionary


Let's understand this with a simple example. First, declare a variable of dictionary type.
test = {}
type(test)

// Result
<class 'dict'>

The variable test is declared as a dictionary type. We will try to add a few keys.
test['a'] = 1
test['b'] = 2
test['c'] = 3

print(test)

// Result
{'a': 1, 'b': 2, 'c': 3}

Now, the test has three keys and values stored: a, b, and c. How can we print all the keys it has?


! Using python dictionary keys() built-in function


The built-in function keys() that can be used on Dictionary (Dictionary) prints all the key information that a Dict type has. Therefore, if you use it on the variable test above, you can check all the key information it has.
print(test.keys())

// Result
dict_keys(['a', 'b', 'c'])

This way, you can confirm that it has three keys: a, b, and c. By using keys(), you can easily check all key information like this.


@ How to check if it has a specific key?
If you need to check if it has a specific key? In this case, you can use the in keyword on Dictionary in the same way.
'a' in test

// Result
True

'd' in test

// Result
False

We tested the variable test above to see if it has the keys a and d. The result returned True because it has a, and False because it doesn't have d.


So far, we have learned how to return all key information that the Python Dictionary type has.
Perhaps you're looking for the following text as well?

    Previous

    Python text character replacement method, substitute method, replace()

    Previous

    [Python] Creating random numbers, using random