Pythonic way to create a dictionary from a list where the keys are the elements that are found in another list and values are elements between keys

  • A+
Category:Languages

Considering that I have two lists like:

l1 = ['a', 'c', 'b', 'e', 'f', 'd'] l2 = [     'x','q','we','da','po',     'a', 'el1', 'el2', 'el3', 'el4',     'b', 'some_other_el_1', 'some_other_el_2',     'c', 'another_element_1', 'another_element_2',     'd', '', '', 'another_element_3', 'd4' ] 

and I need to create a dictionary where the keys are those element from second list that are found in the first and values are lists of elements found between "keys" like:

result = {     'a': ['el1', 'el2', 'el3', 'el4'],     'b': ['some_other_el_1', 'some_other_el_2'],     'c': ['another_element_1', 'another_element_2'],     'd': ['', '', 'another_element_3', 'd4'] } 

What's a more pythonic way to do this?

Currently I'm doing this :

# I'm not sure that the first element in the second list will also be in the first so I have to create a key k = '' d[k] = [] for x in l2:     if x in l1:         k = x         d[k] = []     else:         d[k].append(x) 

But I'm quite positive that this is not the best way to do it and it also doesn't looks nice :)

Edit: I also have to mention that no list is necessary ordered and neither the second list must start with an element from the first one.


I don't think you'll do much better if this is the most specific statement of the problem. I mean I'd do it this way, but it's not much better.

import collections  d = collections.defaultdict(list) k = ''  for x in l2:     if x in l1:         k = x     else:         d[k].append(x) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: