In Python, a list is a collection of items that are ordered and changeable. Each item in the list has an index, which starts from 0.
Sometimes, we need to get a key-value pair from a list in Python. This tutorial will show you how to get a key-value from a list in Python.
1. Create a list with key-value pairs
To get a key-value pair from a list, we first need to create a list with key-value pairs. In Python, we can create a list using square brackets [ ] and separate the elements with a comma. Here is an example:
1 |
my_list = [{"key1": "value1"}, {"key2": "value2"}, {"key3": "value3"}] |
In the above example, we have created a list with three dictionaries, each containing a key-value pair.
2. Accessing the key-value pair using index
To access the key-value pair from the list, we can use the index operator [ ]. We pass the index of the dictionary we want to access as an argument to the index operator. Here is an example:
1 |
my_dict = my_list[0] |
In the above example, we are accessing the first dictionary in the list using its index, which is 0. The variable my_dict now contains the first dictionary.
3. Accessing the value of a key in the dictionary
To access the value of a key in the dictionary, we can use the key operator [ ]. We pass the key we want to access as an argument to the key operator. Here is an example:
1 |
my_value = my_dict["key1"] |
In the above example, we are accessing the value of the key “key1” in the dictionary. The variable my_value now contains the value of the key.
4. Putting it all together
Here is an example of how to get a key-value pair from a list using the above steps:
1 2 3 4 |
my_list = [{"key1": "value1"}, {"key2": "value2"}, {"key3": "value3"}] my_dict = my_list[0] my_value = my_dict["key1"] print(my_value) |
In the above example, we are getting the value of the key “key1” from the first dictionary in the list, which is “value1”. We then print the value of my_value, which is “value1”.
By following these simple steps, you can easily get a key-value pair from a list in Python.
Full Code:
1 2 3 4 |
my_list = [{"key1": "value1"}, {"key2": "value2"}, {"key3": "value3"}] my_dict = my_list[0] my_value = my_dict["key1"] print(my_value) |
Output:
value1