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?
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'}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With