Python program to get the keys of a dictionary

Here, we are going to learn how to get the keys of a dictionary in Python?
Submitted by Shivang Yadav, on March 24, 2021

A dictionary contains the pair of the keys & values (represents key : value), a dictionary is created by providing the elements within the curly braces ({}), separated by the commas. 

Here, we are going to access and print the all keys of a dictionary, there are some of the ways to get the keys of a dictionary.

  1. Using loop through a dictionary
  2. Using the keys() method

1) Get the keys of a dictionary by looping through a dictionary

When we loop through a dictionary, it returns the keys only. In this way, we can get and print the all keys of a dictionary.

Syntax:

for key in dictionary_name:
    print(key)

Program:

# Python program to get the keys of a dictionary 
# by looping through a dictionary

# creating the dictionary
dict_a = {'id' : 101, 'name' : 'Amit', 'age': 21}

# printing the dictionaries
print("Dictionary \'dict_a\' is...")
print(dict_a)

# looping through a dictionary
# and, printing the keys
print("Keys of the Dictionary \'dict_a\'...")
for x in dict_a:
    print(x)

Output:

Dictionary 'dict_a' is...
{'name': 'Amit', 'id': 101, 'age': 21}
Keys of the Dictionary 'dict_a'...
name
id
age

2) Get the keys of a dictionary by using the keys() method

The keys() method is a built-in method in Python and it returns a view object containing the keys of the dictionary as a list.

Syntax:

dictionary_name.keys()

Program:

# Python program to get the keys of a dictionary 
# by using the keys() method

# creating the dictionary
dict_a = {'id' : 101, 'name' : 'Amit', 'age': 21}

# printing the dictionaries
print("Dictionary \'dict_a\' is...")
print(dict_a)

# getting the keys of a dictionary
# using keys() method and, printing the keys
print("Keys of the Dictionary \'dict_a\'...")
print(dict_a.keys())

Output:

Dictionary 'dict_a' is...
{'name': 'Amit', 'id': 101, 'age': 21}
Keys of the Dictionary 'dict_a'...
dict_keys(['name', 'id', 'age'])

Python Dictionary Programs »





Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.