me45
me45

Reputation: 1119

two lists into a dictionary

I have two lists created in python like so:

list1 = [2, 3, 3, 4, 4, 5]
list2 = [-4, 8, -4, 8, -1, 2]

Now I zipped these two lists into a dictionary like so:

d = dict(zip(list1, list2))

which gives me:

{2: -4, 3: -4, 4: -1, 5: 2}

What I want to get is a result like this:

{2: -4, 3: 4, 4: 7, 5: 2}

list1 is becoming the the keys to the new dictionary. If I have two values in list1 that are the same, I want it to add the two values. For example, in list2, 8 and -4 both have the same key 3. Is there a way to add these two values together so the key looks like

{3: 4}   

Upvotes: 4

Views: 1869

Answers (4)

Ashok KS
Ashok KS

Reputation: 691

You could try dictionary comprehension to combine two lists into a dictionary .

list1 = [2, 3, 3, 4, 4, 5]
list2 = [-4, 8, -4, 8, -1, 2]

{k:v for k,v in zip(list1,list2)}

Output:

{2: -4, 3: -4, 4: -1, 5: 2}

Upvotes: 0

Raymond Hettinger
Raymond Hettinger

Reputation: 226256

I think you want something like this:

>>> list1 = [2, 3, 3, 4, 4, 5]
>>> list2 = [-4, 8, -4, 8, -1, 2]

>>> d = {}
>>> for k, v in zip(list1, list2):
        d[k] = d.get(k, 0) + v

>>> d
{2: -4, 3: 4, 4: 7, 5: 2}

Upvotes: 10

Karthik Gurusamy
Karthik Gurusamy

Reputation: 769

Just remember when you are sorting, you incur a big cost (O(nlogn)). Also very likely there is an O(n) temporary space (memory) use. dict are designed to do one job best -- and that is fast lookup/add/delete -- not walk all items in a sorted order (walking in unsorted order is still fine). For small number of items, this is not an issue. It's good to identify the right datas-tructure by knowing its strengths and limitations. There are other datastructures like trees which can provide ordered walk without the big cost (they can do it in O(n)).

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 838116

Try using a defaultdict:

from collections import defaultdict

d = defaultdict(int)
for k, v in zip(list1, list2):
    d[k] += v

Result:

defaultdict(<type 'int'>, {2: -4, 3: 4, 4: 7, 5: 2})

See it working online: ideone

Upvotes: 7

Related Questions