How to print a dictionary's key?
To print the keys of a dictionary in Python, you can use the built-in keys() method.
To print the keys of a dictionary in Python, you can use the built-in keys() method. Here is an example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key in my_dict.keys():
print(key)This will output:
a
b
cAnother way to do this is to use the items() method, which returns a list of key-value pairs, and then extract the keys using a list comprehension:
my_dict = {'a': 1, 'b': 2, 'c': 3}
print([key for key, value in my_dict.items()])This will output:
['a', 'b', 'c']In Python 3, dict.keys() returns a view object that can be passed directly to the print() function:
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict.keys())This will output:
dict_keys(['a', 'b', 'c'])