Shaokan Shaokan - 4 years ago 136
Python Question

python convert list to dictionary

l = ["a", "b", "c", "d", "e"]

I want to convert this list to a dictionary like:

d = {"a": "b", "c": "d", "e": ""}

So basically, the evens will be keys whereas the odds will be values. I know that I can do it in a "non-pythonic" way such as a for loop with if statements but I believe that there should be a more "pythonic" way to accomplish this. So, I appreciate any help :)

Answer Source

Using the usual grouper recipe, you could do:

Python 2:

d = dict(itertools.izip_longest(*[iter(l)] * 2, fillvalue=""))

Python 3:

d = dict(itertools.zip_longest(*[iter(l)] * 2, fillvalue=""))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download