2

I have a list (myarray) that looks something like this,

[u 'item-01', 52, u 'item-02', 22, u 'item-03', 99, u 'item-04', 84]

I'm trying to convert this into a dictionary with keys and value.

I've tried looping but doesn't give me the expected results,

mydict = {}
for k,v in myarray:
mydict[k] = v
jumpman8947
  • 427
  • 2
  • 7
  • 17
  • "key called name" and "value called number" sound fishy. A dictionary doesn't have any representation of what its keys and values are called. – user2357112 Dec 23 '15 at 17:21
  • Possible duplicate of [How do you split a list into evenly sized chunks in Python?](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python) – GingerPlusPlus Dec 23 '15 at 17:23

2 Answers2

6

Simple: Use zip and extended slicing.

mydict = dict(zip(myarray[::2], myarray[1::2]))

The first extended slice makes a list of all even indices, the second of all odd, the zip pairs them up into tuples, and the dict constructor can take an iterable of paired values and initialize using them as key/value pairs.

Note: Padraig's solution of using iter will work faster (and handle non-sequence iterables), though it is somewhat less intuitive (and not quite as succinct as written). Of course, it can be one-lined at the expense of becoming even less intuitive by using the behavior of list multiplication copying references (see Note 2 on the table of sequence operations; an example of another use for it is found in the itertools grouper recipe):

mydict = dict(zip(*[iter(myarray)]*2))
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
4

You can combine iter and zip:

l = [u'item-01', 52, u'item-02', 22, u'item-03', 99, u'item-04', 84]

it = iter(l)

print(dict(zip(it, it)))
{u'item-04': 84, u'item-01': 52, u'item-03': 99, u'item-02': 22}

zip(it, it) creates pairs combining every two elements, calling dict on the result uses the first element of each tuple as the key and the second as the vale.

In [16]: it = iter(l)

In [17]: l = list(zip(it,it))

In [18]: l
Out[18]: [('item-01', 52), ('item-02', 22), ('item-03', 99), ('item-04', 84)]

In [19]: dict(l)
Out[19]: {'item-01': 52, 'item-02': 22, 'item-03': 99, 'item-04': 84}

Using a for loop like your own code:

it = iter(l)
d = {}
for k, v in it:
    d[k] = v
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321