DEV Community

Kevin Naidoo
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",
    "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.

Top comments (8)

Collapse
 
fabrixi profile image
Fabrizio
search_tags_dict = dict(zip(search_tags[::2], search_tags[1::2]))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kwnaidoo profile image
Kevin Naidoo

Nice! Very compact.

Collapse
 
robertgroves profile image
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)
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kwnaidoo profile image
Kevin Naidoo

Nice! This is indeed correct.

Collapse
 
ryanlwh profile image
Ryan Lee • Edited
from itertools import pairwise
search_tags_dict = dict(pairwise(search_tags))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ptmcg profile image
Paul McGuire
search_iter = iter(search_tags)
search_tags_dict = dict(zip(search_iter, search_iter))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kwnaidoo profile image
Kevin Naidoo

Great! Another good way of doing it.

Collapse
 
fialex137 profile image
fialex137 • Edited

This is my solution!!!

Image description