Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

create a dictionary from the lists based on string match

I have two list of files as follows:

L3 = ['D://carrot_25kg', 'D://banana_5kg', 'D://apple_50kg']
L4 = ['D://box3_5kg-mark', 'D://box1_25kg-dan', 'D://box2_50kg-jack']

I needed to group files as follows.

result = [['D://carrot_25kg', 'D://box1_25kg-dan'],
          ['D://banana_5kg', 'D://box3_5kg-mark'],
          ['D://apple_50kg', 'D://box1_50kg-jack']] #the order is not important

It is to match based on "_xxkg" string. How can I do it guys?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

from collections import defaultdict
from itertools import chain    

d = defaultdict(list)

for path in chain(L3, L4):
    suffix = path.split('_')[-1]
    d[suffix].append(path)

the result is unexpected.

defaultdict(<class 'list'>, {'25kg': ['D://carrot_25kg'], '5kg': ['D://banana_5kg'], '50kg': ['D://apple_50kg'], '5kg-mark': ['D://box3_5kg-mark'], '25kg-dan': ['D://box1_25kg-dan'], '50kg-jack': ['D://box2_50kg-jack']})

>Solution :

You’re not removing the -xxxx part when you form the dictionary key. Use

suffix = path.split('_')[-1].split('-')[0]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading