Reputation: 3557
If I have a large list that I want to create a dictionary out of, what would be the most efficient way of doing this supposing I just want to assign the value as so:
{'item1':'0','item2':'1','item3':'2','itemn':'n-1'}
I've seen a lot on here about just assigning same value to all the keys, but nothing about how to assign the values as I need.
Thanks.
EDIT: The reason I want to do this is because I've been handed someone's code that is atrocious...(not that I'm a skilled programmer by any means), and we have a list of objects that are represented by ID numbers: 5432, 8976, etc etc.
There's a few hundred of them. Well rather than, as the original code does, treat the list as an array, then find its range(len(my_list))
to get an indicial value for each object, I was thinking it might be better to just create a dictionary with keys/values, declare that once and refer to it later rather than recalling the array or -in this case- recreating the array every time. Is that a reasonable idea? I don't know, but I wanted to try it.
Upvotes: 2
Views: 219
Reputation: 3606
The answer seems to depend on which version of Python you are using.
These are my results with IPython 0.13 on Python 2.7.3:
In [11]: mylist = ["item{}".format(i) for i in range(10**7)]
In [12]: %timeit d = dict(zip(mylist, range(len(mylist))))
1 loops, best of 3: 6.97 s per loop
In [13]: %timeit d = {item: i for i, item in enumerate(mylist)}
1 loops, best of 3: 3.68 s per loop
In [14]: # Edit: xrange is faster than range in Python 2
In [15]: %timeit d = dict(zip(mylist, xrange(len(mylist))))
1 loops, best of 3: 5.58 s per loop
And this is what I get with IPython 0.13 on Python 3.3.2:
In [5]: mylist = ["item{}".format(i) for i in range(10**7)]
In [6]: %timeit d = dict(zip(mylist, range(len(mylist))))
1 loops, best of 3: 2.62 s per loop
In [7]: %timeit d = {item: i for i, item in enumerate(mylist)}
1 loops, best of 3: 2.92 s per loop
This is probably because zip
doesn't return a list in Python 3 but only an iterator…
Upvotes: 1
Reputation: 3606
If you don't care about the assigned values for now, the fastest way to build a dict from a list is dict.fromkeys(mylist)
:
In [13]: mylist = ["stuff", "more stuff"]
In [14]: dict.fromkeys(mylist)
Out[14]: {'more stuff': None, 'stuff': None}
Upvotes: 0
Reputation: 113950
dict(("item%d"%i,val) for i,val in enumerate(my_list,1))
presumably
Upvotes: 0