Python challenge: can you solve this in a readable and efficient way?

Kevin Naidoo - Feb 13 - - Dev Community

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"
]
Enter fullscreen mode Exit fullscreen mode

"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
Enter fullscreen mode Exit fullscreen mode

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.
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .