The keys method of dictionary class

Method Name:

keys

Method Signature:

keys()

Method Overview:

  • The keys() method returns all the keys of a Python dictionary instance as a dict_keys.
  • The returned dict_keys changes its view as the keys of the original dictionary instance changes.

Parameters:

None

Return Value:

The keys of the dictionary as an instance of dict_keys class.

Example:

# Example Python program that retrieves
# all the keys of a dictionary as a dict_keys
airports = {"ATL":"Hartsfield Atlanta International",
             "BWI":"Washington DC - Baltimore Washington International",
             "DFW":"Dallas/Fort Worth International" ,
             "JFK":"New York - John F. Kennedy",
             "LAX":"Los Angeles",
             "ORD":"Chicago - O'Hare International",
             "SFO":"San Francisco",
           };

airport_codes = airports.keys();

print("Dictionary view:");

# Iterate the view and print the airport codes
for code in airport_codes:
    print(code);

# Add more airport codes
airports["EWR"] = "Newark";
airports["DEN"] = "Denver";

# Print the view after changes to the original dictionary
print("New dictionary view:");
for code in airport_codes:
    print(code);

Output:

Dictionary view:
ATL
BWI
DFW
JFK
LAX
ORD
SFO
New dictionary view:
ATL
BWI
DFW
JFK
LAX
ORD
SFO
EWR
DEN

 


Copyright 2024 © pythontic.com