본문 바로가기
개념/혼자 공부하는 파이썬

python) items

by kiseno 2024. 11. 11.
728x90
반응형
SMALL
example_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}

print("dictionary: ")
print("items() : ", example_dict.items())
print()

print("dictionary items() function and loop syntax combine")
for key,  element in example_dict.items():
    print("dictionary[{}] = {}".format(key, element))

This code snippet demonstrates how to interact with a dictionary in Python, specifically showcasing how to access and iterate over its items using the `.items()` method. Here's a breakdown of what each part of the code does:

### Dictionary Initialization

1. **`example_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}`**: This line initializes a dictionary named `example_dict` with three key-value pairs. In Python, dictionaries are collections of key-value pairs where each key is unique.

### Printing Dictionary Items

2. **`print("dictionary: ")`**: Prints the string `"dictionary: "` to the console, serving as a header or introduction to the output that follows.

3. **`print("items() : ", example_dict.items())`**: The `.items()` method returns a view object that displays a list of dictionary's key-value tuple pairs. This line prints the string `"items() : "` followed by the key-value pairs of `example_dict` as returned by the `.items()` method.

4. **`print()`**: Prints an empty line for better readability between different sections of the output.

### Iterating Over Dictionary Items

5. **`print("dictionary items() function and loop syntax combine")`**: Prints a header string indicating that the upcoming code demonstrates combining the `.items()` method with a loop to iterate over dictionary items.

6. **`for key, element in example_dict.items():`**: Begins a for-loop that iterates over each key-value pair in the dictionary. The `.items()` method is used here to get each item as a tuple of `(key, element)`, where `key` is the key and `element` is the corresponding value in the dictionary.

7. **`print("dictionary[{}] = {}".format(key, element))`**: Inside the loop, this line prints each key-value pair in the format `dictionary[key] = value`. The `.format(key, element)` method replaces the `{}` placeholders with the values of `key` and `element`, respectively.

This snippet efficiently demonstrates how to work with dictionaries in Python, specifically how to access all items in a dictionary and how to iterate over them using a for-loop. The use of `.items()` is a common and powerful way to access both keys and values during iteration, allowing for concise and readable code when dealing with dictionaries.

728x90
반응형
LIST