w3resource

Python: Create a given flat list of all the keys in a flat dictionary

Python List: Exercise - 258 with Solution

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:

Flowchart: Create a given flat list of all the keys in a flat dictionary.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/list/python-data-type-list-exercise-258.php