w3resource

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

Python dictionary: Exercise-78 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 'test' that takes a dictionary 'flat_dict'.
# The function returns a list of keys from the given dictionary.
def test(flat_dict):
    # Use the 'keys' method to extract all the keys from the dictionary and convert them to a list.
    return list(flat_dict.keys())

# Create a dictionary 'students' with key-value pairs.
students = {
    'Theodore': 19,
    'Roxanne': 20,
    'Mathew': 21,
    'Betty': 20
}

# Print the original dictionary.
print("\nOriginal dictionary elements:")
print(students)

# Call the 'test' function to create a flat list of all the keys in the 'students' dictionary.
print("\nCreate a flat list of all the keys of the said flat dictionary:")
print(test(students)) 

Sample Output:

Original dictionary elements:
{'Theodore': 19, 'Roxanne': 20, 'Mathew': 21, 'Betty': 20}

Create a flat list of all the keys of the said flat dictionary:
['Theodore', 'Roxanne', 'Mathew', 'Betty']

Flowchart:

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

Python Code Editor:

Previous: Write a Python program to convert given a dictionary to a list of tuples.
Next: Write a Python program to create a flat list of all the values in a flat dictionary.

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/dictionary/python-data-type-dictionary-exercise-78.php