Walid Mujahid Walid Mujahid - 1 year ago 96
Python Question

How to convert a list to a dictionary where both key and value are the same?

This is based on this question: python convert list to dictionary

The asker provides the following:

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

I want to convert this list to a
dictionary like:

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

While the grouper recipe is quite interesting and I have been "playing" around with it, however, what I would like to do is, unlike the output dictionary wanted by that asker, I would like to convert a list with strings like the one above into a dictionary where all values and keys are the same. Example:

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

How would I do this?

Answer Source

You can just zip the same list together:

dict(zip(l, l))

or use a dict comprehension:

{i: i for i in l}

The latter is faster:

>>> from timeit import timeit
>>> timeit('dict(zip(l, l))', 'l = ["a", "b", "c", "d", "e"]')
>>> timeit('{i: i for i in l}', 'l = ["a", "b", "c", "d", "e"]')

This holds even for large sequences:

>>> timeit('dict(zip(l, l))', 'l = range(1000000)', number=10)
>>> timeit('{i: i for i in l}', 'l = range(1000000)', number=10)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download