Python - add to dictionary based on incremental value in 2 lists

I have 2 lists that I created and added a value for each item. The reason is that the values ​​in each list must be combined in a dictionary. However, the values ​​in each list are not a pair of 1 to 1, so I added extra values ​​to help associate each key with the corresponding values.

Here are some examples from my lists:

list_a = ['abc|1','bcd|2','cde|3'] list_b = ['1234|1','2345|2','3456|2','4567|2','5678|3'] 

Ideally, what I'm looking for is done through both lists, and then creates a dictionary based on pairing in increasing values. I assume that the values, where applicable, should be a list?

Below is the perfect solution:

 my_dict = {'abc|1':'1234|1','bcd|2':['2345|2','3456|2','4567|2'],'cde|3':'5678|3'} 

Any help would be greatly appreciated, Thanks in advance :)

+5
source share
4 answers
 list_a = ['abc|1','bcd|2','cde|3'] list_b = ['1234|1','2345|2','3456|2','4567|2','5678|3'] tmp = {k.split('|')[1]: (k, []) for k in list_a} for v in list_b: tmp[v.split('|')[1]][1].append(v) my_dict = dict(tmp.values()) 

This is close to what you set as your goal, but I think it’s really better.

 goal: {'abc|1': '1234|1', 'bcd|2': ['2345|2', '3456|2', '4567|2'], 'cde|3': '5678|3' } mine: {'abc|1': ['1234|1'], 'bcd|2': ['2345|2', '3456|2', '4567|2'], 'cde|3': ['5678|3']} 

You can see that we differ only in that we add singles to the list (of me) or not (you). The reason I think my way is better is that any code using this result will be easier if all the values ​​are lists, so it does not need to process both single lines and line lists. Just as it was easier for me to create only lists.

But if you still prefer your way, change my previous line to:

 my_dict = {k: v if len(v) > 1 else v[0] for k, v in tmp.values()} 
+2
source

You can do two dicts groupings with the first:

 list_a = ['abc|1','bcd|2','cde|3'] list_b = ['1234|1','2345|2','3456|2','4567|2','5678|3'] d = defaultdict(list) from itertools import chain for k in chain(list_a,list_b): d[k.rsplit("|",1)[1]].append(k) print(d) print({v[0]:v[1:] for v in d.values()}) defaultdict(<type 'list'>, {'1': ['abc|1', '1234|1'], '3': ['cde|3', '5678|3'], '2': ['bcd|2', '2345|2', '3456|2', '4567|2']}) {'abc|1': ['1234|1'], 'cde|3': ['5678|3'], 'bcd|2': ['2345|2', '3456|2', '4567|2']} 

You can avoid the list for single values ​​by first checking the length if necessary.

 d = {v[0]: (v[1:] if len(v)> 2 else v[-1]) for v in d.values()} print(d) {'abc|1': '1234|1', 'cde|3': '5678|3', 'bcd|2': ['2345|2', '3456|2', '4567|2']} 

Using python3, the syntax is slightly better using extended iterative unpacking :

 d = {k: (val if len(val) > 1 else val[0]) for k,*val in d.values()} print(d) 

If you need an order based on the keys in the list, you will need OrderedDict:

 list_a = ['abc|1', 'bcd|2', 'cde|3'] list_b = ['1234|1', '2345|2', '3456|2', '4567|2', '5678|3'] from collections import OrderedDict from itertools import chain od = OrderedDict() for k in chain(list_a, list_b): od.setdefault(k.rsplit("|",1)[1], []).append(k) d = OrderedDict((k, (val)) for k, *val in od.values()) 
+2
source

It can be achieved from something like this.

 temp_dict = {} for x in list_a: val = x.split('|')[1] temp_dict[x] = [y for y in list_b if y.endswith("|" + val)] 
+2
source

Here is a very readable code, it should be clear enough, but if in doubt, please comment. You can use OrderedDict instead of the usual dict () if you want to keep the key order as they are added to the dictionary.

 list_a = ['abc|1','bcd|2','cde|3'] list_b = ['1234|1','2345|2','3456|2','4567|2','5678|3'] d = dict() for item in list_a: d.update({item:[]}) # initialize the dictionary value_a = item.split('|')[1] # extract the number from the item of list_a for thing in list_b: value_b = thing.split('|')[1] # extract the number from the item of list_b if value_a == value_b: # if the numbers are the same d[item].append(thing) # append the item of list_b into the dictionary print(d) 
0
source

All Articles