Creating a dictionary from a list in Python
If L
is your original list, you can use zip(*[iter(L)]*2)
to group items into pairs. The dict constructor can accept the iterable of such pairs directly
>>> L = ['name1', 'value1', 'name2', 'value2', 'name3', 'value3']
>>> dict(zip(*[iter(L)]*2))
{'name1': 'value1', 'name2': 'value2', 'name3': 'value3'}
I'm not sure what you mean by simpler (easier to understand?). It's hard to guess if you think this is easier as I don't know what level you are at. Here is the way without using iter
or zip
. If you don't already know what enumerate
, you should watch it.
>>> d = {}
>>> for i, item in enumerate(L):
... if i % 2 == 0:
... key = item
... else:
... d[key] = item
...
>>> d
{'name1': 'value1', 'name2': 'value2', 'name3': 'value3'}
source to share
You need a function to group a sequence into fixed length chunks. Unfortunately this is missing from the Python core. You can use partition
in the library funcy . (Note: in other languages ββthis is called chunksOf or grouped ).
The itertools documentation offers this feature:
from itertools import zip_longest
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
And the zip documentation suggests another way to accomplish the same thing (quoted in gnibbler's answer ):
def grouper(iterable, n):
return zip(*[iter(iterable)]*n)
Once it is available, the rest of the assignment will be trivial.
>>> dict(grouper(range(8), 2))
{0: 1, 2: 3, 4: 5, 6: 7}
source to share
You can try this
>>> a = ['a', 'b', 'c', 'd', 'e', 'f']
>>> dict(zip([x for x in a[::2]], [x for x in a[1::2]]))
{'a': 'b', 'c': 'd', 'e': 'f'}
a[::2]
will get the entire second element from the beginning of the list from the element 0th
.
a[1::2]
will get the entire second element from the beginning of the list from the element 1st
.
source to share