0

I would like to create a dictionary from list

>>> list=['a',1,'b',2,'c',3,'d',4]
>>> print list
['a', 1, 'b', 2, 'c', 3, 'd', 4]

I use dict() to produce dictionary from list but the result is not in sequence as expected.

>>> d = dict(list[i:i+2] for i in range(0, len(list),2))
>>> print d
{'a': 1, 'c': 3, 'b': 2, 'd': 4}

I expect the result to be in sequence as the list.

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Can you guys please help advise?

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
  • 1
    Keys in a dictionary are not ordered. Why do you expect this order? Because it's the same as in the list or because it is lexigographical? Maybe you don't need a dictionary. Can you add more informations about how you are going to use "d"? – jimifiki Aug 24 '13 at 10:02

3 Answers3

4

Dictionaries don't have any order, use collections.OrderedDict if you want the order to be preserved. And instead of using indices use an iterator.

>>> from collections import OrderedDict
>>> lis = ['a', 1, 'b', 2, 'c', 3, 'd', 4]
>>> it = iter(lis)
>>> OrderedDict((k, next(it)) for k in it)
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
4

You could use the grouper recipe: zip(*[iterable]*n) to collect the items into groups of n:

In [5]: items = ['a',1,'b',2,'c',3,'d',4]

In [6]: items = iter(items)

In [7]: dict(zip(*[items]*2))
Out[7]: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

PS. Never name a variable list, since it shadows the builtin (type) of the same name.

The grouper recipe is easy to use, but a little harder to explain.

Items in a dict are unordered. So if you want the dict items in a certain order, use a collections.OrderedDict (as falsetru already pointed out):

In [13]: collections.OrderedDict(zip(*[items]*2))
Out[13]: OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • I'll just note that `items = iter(items)` could lead to subtle problems if `items` is expected to be used as a list later... – Jon Clements Aug 24 '13 at 13:01
4

Dictionary is an unordered data structure. To preserve order use collection.OrderedDict:

>>> lst = ['a',1,'b',2,'c',3,'d',4]
>>> from collections import OrderedDict
>>> OrderedDict(lst[i:i+2] for i in range(0, len(lst),2))
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
falsetru
  • 357,413
  • 63
  • 732
  • 636