Two lists in a dictionary

I have two lists created in python:

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

Now I have fixed these two lists in the dictionary as follows:

 d = dict(zip(list1, list2)) 

which gives me:

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

I want to get this result:

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

list1 becomes the key to the new dictionary. If I have two values ​​in list1 that are the same, I want them to add two values. For example, in list 2, 8, and -4, both have the same key 3. Is there a way to add these two values ​​together so that the key looks like

 {3: 4} 
+4
source share
3 answers

I think you need 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} 
+10
source

Try using 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 how it works on the Internet: ideone

+7
source

Remember, when you sort, you take a lot of cost (O (nlogn)). It is also very likely to use O (n) temporary space (memory). dict are designed to do one job best - and this is a quick search / add / delete - do not walk all items in sorted order (walking in unsorted order is still beautiful). For a small number of items, this is not a problem. It is good to identify the correct data structure, knowing its strengths and limitations. There are other data structures, such as trees, that can provide an orderly walk at no cost (they can do this in O (n)).

0
source

Source: https://habr.com/ru/post/1383239/


All Articles