-3

Is there no one function that will iterate over a list of strings or strings and integers and populate a dictionary like so:

{list[0] : list[1]
list[2] : list[3]
list[4] : list [5]}

I've seen 40 different ways of doing it that are more complicated than if there was just one function that did it. I would think wanting to converting a list of strings to a dictionary is not an esoteric thing to want to do.

Does this exist? If it does exist, what's the function called?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Argentus
  • 7
  • 1
  • 2
    No. But you can create a dictionary from an iterable of 2-tuples, which is easy to create from a list. It's weird to have a list that's heterogeneous, such that keys and values alternate. – jonrsharpe Apr 13 '23 at 22:43
  • 1
    Or you can take one of the 40 ways and put it _in_ a function. – jonrsharpe Apr 13 '23 at 22:48

3 Answers3

0

For a given list L, here is a quick one-line approach to produce a dictionary in this fashion:

result = dict(zip(L[::2],L[1::2]))
Ben Grossmann
  • 4,387
  • 1
  • 12
  • 16
  • Okay, thanks for this. After pestering ChatGPT with several versions of this question, it also suggested this after suggesting 2 or 3 other more clunky things. – Argentus Apr 13 '23 at 22:55
  • This code would iterate over the list twice, which could be ineffective and might not work with other sequences/iterables. – Nikolaj Š. Apr 18 '23 at 17:47
0

For Python 3.12+:

from itertools import batched
it = range(6)
print(dict(batched(it, n=2)))
{0: 1, 2: 3, 4: 5}

Other implementations of batched for earlier Python versions coud be found here: How do I split a list into equally-sized chunks?

Nikolaj Š.
  • 1,457
  • 1
  • 10
  • 17
-1

The least stupid way to do this that I've found is to split the list into 2 lists with for loops where: newlist1 = [list[0] , list[2], list [3]], etc. newlist2 = [list[1] , list[3], list [4]], etc. Then you can zip them into a list of tuples with zip() and then convert the list of tuples into a dict with dict(). Trying to do it all in one for loop has consistently caused me problems if the list is comprised of some mix of strings and integers and it's more confusing to set the for loop statement up right. Since I was looking for assistance with homework issues, this solution also teaches you about a few other functions to boot.

Argentus
  • 7
  • 1