How to use function keys in Python? - with practical example
Sure, here is the script:
---
Hey there! In Python, the keys() function is used to return a view object that displays a list of all the keys in a dictionary. Let's dive into two examples to see how we can use the keys() function.
Example 1:
In this example, we will create a dictionary and then use the keys() function to retrieve all the keys in the dictionary.
Step 1: Create a dictionary
Step 2: Use the keys() function to get all the keys
Step 3: Print the keys
In this example, we first create a dictionary with key-value pairs. We then use the keys() function to retrieve all the keys from the dictionary and store them in a variable. Finally, we print the keys to see the output. Example 2: In this example, we will demonstrate how to iterate over the keys of a dictionary using the keys() function. Step 1: Create a dictionary Step 2: Iterate over the keys using a for loop Step 3: Print each key
In this example, we create a dictionary with key-value pairs. We then use a for loop to iterate over the keys of the dictionary by calling the keys() function. Inside the loop, we print each key to the console. And that's how you can use the keys() function in Python to retrieve and iterate over keys in a dictionary. Hope you found this helpful!
# Create a dictionary my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'} # Get all the keys using keys() function keys = my_dict.keys() # Print the keys print(keys)
In this example, we first create a dictionary with key-value pairs. We then use the keys() function to retrieve all the keys from the dictionary and store them in a variable. Finally, we print the keys to see the output. Example 2: In this example, we will demonstrate how to iterate over the keys of a dictionary using the keys() function. Step 1: Create a dictionary Step 2: Iterate over the keys using a for loop Step 3: Print each key
# Create a dictionary my_dict = {'name': 'Bob', 'age': 25, 'city': 'Los Angeles'} # Iterate over the keys using keys() function for key in my_dict.keys(): print(key)
In this example, we create a dictionary with key-value pairs. We then use a for loop to iterate over the keys of the dictionary by calling the keys() function. Inside the loop, we print each key to the console. And that's how you can use the keys() function in Python to retrieve and iterate over keys in a dictionary. Hope you found this helpful!
Comments
Post a Comment