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'}
>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)