B
Bart Nessux
What is the easiest/fastest way to build a dictionary from a list? The
list contains 100,000 entries.
Thanks,
Bart
list contains 100,000 entries.
Thanks,
Bart
{1: 'a', 2: 'b'}Bart said:What is the easiest/fastest way to build a dictionary from a list? The
list contains 100,000 entries.
Thanks,
Bart>>> dict([(1,'a'),(2,'b')])
Bart said:What is the easiest/fastest way to build a dictionary from a list? The
list contains 100,000 entries.
Peter said:A dictionary has key/value pairs. How do you want to map
the elements of your list to this format? In pairs, or
are you using them all as keys, or something else?
-Peter
What is the easiest/fastest way to build a dictionary from a list? The
list contains 100,000 entries.
Bart said:Peter said:A dictionary has key/value pairs. How do you want to map
the elements of your list to this format? In pairs, or
are you using them all as keys, or something else?
-Peter
1 = book1
2 = book2
3 = book3
etc...
>>> dict(enumerate(['a','b','c'])) {0: 'a', 1: 'b', 2: 'c'}
>>>
Bart said:1 = book1
2 = book2
3 = book3
etc...
Josef said:The first question would be, what should the keys be? If the list consists of unique, unmutable items, then you might use the items themselves as key and write:
mydict = dict(zip(mylist, mylist))
obtaining a dictionary with all the keys and values identical (therefore somewhat of a waste, but occasionally useful). Note: if your original list did not contain unique values, you end up with a set.
If you want to remember the original order of the list, then write
mydict = dict(zip(mylist, xrange(len(mylist))))
If you don't care about the key (that would be strange) then you can write:
mydict = dict(zip(xrange(len(mylist)), mylist))
Instead of len(mylist) you can also write 1000000 or any other number larger than your list.
- Josef
Larry said:If the keys are just indexes that you would
use in the dictionary, you don't need a
dictionary at all. Just index into the list.
list[0]->'book1'
list[1]->'book2'
list[2]->'book3'
You will need to deal with the indexes beginning
at zero (not 1) or put None in list[0] an then
don't reference it.
HTH,
Larry Bates
Syscon, Inc.
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.