DEV Community

Kevin Naidoo

Posted on • Updated on

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

I have a list of search terms and their associated "metadata":

``````search_tags = [
"iPhone 14",
"Samsung Galaxy S3",
"Xiaomi Mi Smart Kettle Pro",
]
``````

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

Assume that the data will always have "search term", "metadata" pairs for each item.

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.

Fabrizio
``````search_tags_dict = dict(zip(search_tags[::2], search_tags[1::2]))
``````

Kevin Naidoo

Nice! Very compact.

Robert Groves
``````search_dict = {}
for i in range(0, len(search_tags), 2):
key = search_tags[i]
search_dict[key] = search_tags[i + 1]

# ...or the same using a list comprehension...

search_dict = {
search_tags[i]: search_tags[i + 1]
for i in range(0, len(search_tags), 2)
}
``````

Kevin Naidoo

Nice! This is indeed correct.

Ryan Lee • Edited
``````from itertools import pairwise
search_tags_dict = dict(pairwise(search_tags))
``````

Paul McGuire
``````search_iter = iter(search_tags)
search_tags_dict = dict(zip(search_iter, search_iter))
``````

Kevin Naidoo

Great! Another good way of doing it.