AnarKi
AnarKi

Reputation: 997

Create dictionary from list elements in Python

I have a list similar to the following:

my_list =
    [(1, 'item_19'),
     (2, 'item_20'),
     (3, 'item_21'),
     (4, 'item_22'),
     (5, 'item_23'),
     (6, 'item_24'),
     (7, 'item_25'),
     (8, 'item_26'),
     (9, 'item_27'),
     (10, 'item_28'),
     (11, 'item_29'),
     (12, 'item_30'),
     (13, 'item_31'),
     (14, 'item_32'),
     (15, 'item_33'),
     (16, 'item_34'),
     (17, 'item_35')]

I would like to make a dictionary of each element of the list, i.e. 1:'item_19',2:'item_20'

I currently do this:

list_1 = [l[0] for l in my_list]
list_2 = [l[1] for l in my_list] 

and then zip the two lists

my_dict = dict(zip(list_1,list_2))

However there are more than a million element in my_list, so is this the best way to do this, or is there a quicker/more optimal way to do it(Memory wise).

To put this in context, I want a lookup table to check if elements in my_dict already exist in a different dictionary my_dict_old

Upvotes: 0

Views: 2606

Answers (2)

Kellen
Kellen

Reputation: 611

The builtin dict function takes a list of tuples, which is exactly what you are providing:

>>> list_foo = [(1, 'item_1'), (2, 'item_2')]
>>> dict(list_foo)
{1: 'item_1', 2: 'item_2'}

If all you need to do is check for an item's existence, consider using set, as i in my_set is much faster than i in my_dict.values(), see the Python documentation on performance for more info. On my machine, for example, a lookup in a haystack of 10k entries is .443s with dict.values(), vs <.000s for set. If you need to associate values with the entries, then use a dictionary, otherwise use a set. For a more in-depth examination of lists vs. dictionaries (and also sets for the most part), refer to this answer.

Upvotes: 2

awesoon
awesoon

Reputation: 33701

dict accepts list of tuples, so you can just use your original list:

my_dict = dict(my_list)

And you are actually doing the same thing while calling zip

Also, if all keys are numbers and are not huge you can put all of them into array. Index would be the key. Though this solution depends on the actual task and might not be useful in some cases

Upvotes: 0

Related Questions