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

Trying to pull all the values that matches the key into one key

I’ve been trying to simply just pull all the values that matches the key into one key. I can’t wrap my head around on how to do this. Please help.

list_dir = ['192586_Sample_010_Test.pdf', '192586_Sample_020_Test.pdf', '192586_Sample_050_Test.pdf', '192120_Sample_020_Test.pdf', '192120_Sample_050_Test.pdf', '192163_Sample_010_Test.pdf', '192163_Sample_020_Test.pdf', '192145_Sample_010_Test.pdf', '192145_Sample_020_Test.pdf', '192145_Sample_050_Test.pdf', '192051_Sample_010_Test.pdf', '192051_Sample_020_Test.pdf', '192051_Sample_050_Test.pdf']
dict = {}

match = []
for i in list_dir:
    match.append((i.split("_", 1)[-2]))

for i in match:
    for x in list_dir:
        if i in x:
            dict[i] = list_dir

print(dict)

Output I’m looking for is

{'192586': '192586_Sample_010_Test.pdf', '192586_Sample_020_Test.pdf', '192586_Sample_050_Test.pdf', 
'192120': '192120_Sample_020_Test.pdf', '192120_Sample_050_Test.pdf', 
'192163': '192163_Sample_010_Test.pdf', '192163_Sample_020_Test.pdf', 
'192145': '192145_Sample_010_Test.pdf', '192145_Sample_020_Test.pdf', '192145_Sample_050_Test.pdf', 
'192051': '192051_Sample_010_Test.pdf', '192051_Sample_020_Test.pdf', '192051_Sample_050_Test.pdf'}

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

>Solution :

Just extract the key from the string and check if it’s in the dict or not. If so append to the list otherwise create a new list.

Like this:

dict = {}

for i in list_dir:
    key = i.split("_")[0]
    
    if key in dict:
        dict[key].append(i)
    else:
        dict[key] = [i]

print(dict)
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