1

I have a list that looks like this:

mylist = [1, 'a', 2, 'b', 3, 'c']

and would like to end up with a dictionary:

mydict = {
    'a': 1,
    'b': 2,
    'c': 3,}

At the moment I'm achieving it like so:

mydict = {}
for i, k in enumerate(mylist):
    if i == len(mylist)/2:
        break
    v = 2 * i
    mydict[mylist[v+1]] = mylist[v]

Is there a more pythonic way of achieving the same thing? I looked up the itertools reference but didn't find anything in particular that would help with the above.

Note: I'm happy with what I have in terms of achieving the goal, but am curious if there is anything that would be more commonly used in such a situation.

pandita
  • 4,739
  • 6
  • 29
  • 51

1 Answers1

2

Try this

# keys
k = mylist[1::2]
# values
v = mylist[::2]
# dictionary
mydict = dict(zip(k, v))
gofvonx
  • 1,370
  • 10
  • 20
  • 2
    The keys and values are reversed, so you should reverse `mylist` first. It will also be better to save the created list to a variable so it won't be created twice in memory, just in case it's a big list. – DeepSpace Oct 07 '18 at 10:51