简体   繁体   中英

create dictionary from list - in sequence

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?

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)])

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)])

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)])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM