1

I have a dictionary which looks something like this:

dicts = 
{"A" : ['shape_one.csv','shape_two.csv','volume_one.csv','volume_two.csv'],
"B" : ['shape_one.csv','shape_two.csv','volume_one.csv','volume_two.csv']}

All the values inside the list of values are paths of a .csv file which I extracted using os.walk(). Now I want to just extract the values which have the string "volume_" in them, and store these values in a list. I want to do this for each key in the dictionary.

I am using python 3.8. I would appreciate any help, as I am a non-programmer just trying to finish a task programmatically. thank you in advance.

The output should return seperate lists for each key, even if the values share the same name.

volume_list_A = ['volume_one.csv','volume_two.csv']

volume_list_B = ['volume_one.csv','volume_two.csv']

I have tried doing: volume_list = [x for x in list(dicts.values()) if "volume_" in x]

but this just returns an empty list.

VasudeV
  • 11
  • 2

1 Answers1

1

Use a list comprehension in a dictionary comprehension:

dicts = {"A" : ['shape_one','shape_two','volume_one','volume_two'],
         "B" : ['shape_one','shape_two','volume_one','volume_two']}

out = {f'volume_list_{k}': [x for x in l if x.startswith('volume_')]
       for k,l in dicts.items()}

NB. if you want volume_ anywhere in the string (not only in the beginning) use if 'volume_' in x in place of if x.startswith('volume_').

Output:

{'volume_list_A': ['volume_one', 'volume_two'],
 'volume_list_B': ['volume_one', 'volume_two']}
mozway
  • 194,879
  • 13
  • 39
  • 75
  • Thank you. I will try this. Can you please see the edit I have made and see if this response still works ? – VasudeV Apr 14 '23 at 11:58
  • @VasudeV yes, this should still work – mozway Apr 14 '23 at 12:05
  • Thanks. This solves my problem for now. I want to know though, how do I get independent lists instead of dictionary of lists ? – VasudeV Apr 14 '23 at 12:07
  • You should not try to generate variable names dynamically, [this is a very bad practice](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables). Instead access the lists using `out['volume_list_A']`. Or keep the original key: `out = {k: [x for x in l if x.startswith('volume_')] for k,l in dicts.items()}` then `out['A']`. – mozway Apr 14 '23 at 12:10