I have a list of search terms and their associated "metadata":
search_tags = [
"iPhone 14",
"metadata",
"Samsung Galaxy S3",
"metadata",
"Xiaomi Mi Smart Kettle Pro",
"metadata"
]
"Metadata" is a dictionary, but for this exercise, I am just using a simple string.
Can you convert: "search_tags" into a dictionary "search_tags_dict". The search term should be the key for each of the "metadata" items.
Comment your answer down below.
Assume that the data will always have "search term", "metadata" pairs for each item.
EDIT: ANSWER
Looking at the comments there are some excellent ways of doing this, thank you to all who attempted the challenge.
Here is my solution:
search_dict = {}
i = 0
size_of_terms = len(search_tags) - 1
while i < size_of_terms:
search_dict[search_tags[i]] = search_tags[i + 1]
i += 2
Why this approach?
- It's not as sexy as range or zip which are great options, however, readability is important. Anyone with basic Python knowledge will find this far easier to understand. Thus, is the ethos of Python: Readability.
- The time complexity is linear, making this approach fairly efficient for the size of this list.
Top comments (8)
Nice! Very compact.
Nice! This is indeed correct.
Great! Another good way of doing it.
This is my solution!!!