Python: Create a given flat list of all the keys in a flat dictionary
Keys of Flat Dictionary
Write a Python program to create a flat list of all the keys in a flat dictionary.
- Use dict.keys() to return the keys in the given dictionary.
- Return a list() of the previous result.
Sample Solution:
Python Code:
# Define a function to extract and return a list of keys from a dictionary.
def keys_only(students):
return list(students.keys()) # Use the keys() method to get the keys from the dictionary.
# Create a dictionary of students with names as keys and their respective grades as values.
students = {
'Laura': 10,
'Spencer': 11,
'Bridget': 9,
'Howard ': 10, # Note: There is an extra space at the end of 'Howard'.
}
# Print the original dictionary elements.
print("Original directory elements:")
print(students)
# Call the 'keys_only' function to extract keys and print them as a flat list.
print("\nFlat list of all the keys of the said dictionary:")
print(keys_only(students))
Sample Output:
Original directory elements: {'Laura': 10, 'Spencer': 11, 'Bridget': 9, 'Howard ': 10} Flat list of all the keys of the said dictionary: ['Laura', 'Spencer', 'Bridget', 'Howard ']
Flowchart:
Python Code Editor:
Previous: Write a Python program to check if two given lists contain the same elements regardless of order.
Next: Write a Python program to check if a given function returns True for at least one element in the list.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics