Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate dictionary from list in Python

Here's the original list:

['name', 'value', 'name', 'value', 'name', 'value']

And so on. I need to extract the name/value pairs into a dictionary:

{'name': 'value', 'name': 'value', 'name': 'value'}

Can someone elaborate on the easiest way to do this?

like image 854
Joshua Gilman Avatar asked Apr 28 '26 16:04

Joshua Gilman


2 Answers

If L is your original list, You can use zip(*[iter(L)]*2) to group the items into pairs. The dict constructor can take an 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 (simpler to understand?). It's hard to guess you think is simpler as I don't know what level you're at. Here's a way without using iter or zip. If you don't know what enumerate does yet, you should look it up.

>>> d = {}
>>> for i, item in enumerate(L):
...     if i % 2 == 0:
...         key = item
...     else:
...         d[key] = item
... 
>>> d
{'name1': 'value1', 'name2': 'value2', 'name3': 'value3'}
like image 126
John La Rooy Avatar answered May 01 '26 07:05

John La Rooy


Not to take away from anyone. I think this might be a little simpler to understand:

dict (zip (L[::2] , L[1::2] ))

Though this is less efficient for large list than gnibbler's answer.

like image 21
Maxaon3000 Avatar answered May 01 '26 07:05

Maxaon3000