 <p>You can use 2 comprehensions to naturally loop over the data structures.</p> <pre><code>dict((drug, [file for file in file_list if drug in file]) for drug in drug_list) </code></pre> <p>Let's break this down. We'll need to create a dictionary, so let's use a list comprehension for that.</p> <pre><code>dict((a, str(a + " is the value")) for a in [1, 2, 3]) </code></pre> <p>The outermost part is a list comprehension that creates a dict. By creating 2-tuples of the form (key, value) we can then simply call dict() on it to get a dictionary. In our answer, we set the drug as the key and we set the value to a list that is built from another list comprehension. So far we have:</p> <pre><code>{'17A': [SOMETHING], '56B': [SOMETHING], '96A': [SOMETHING]} </code></pre> <p>Now we need to fill in the SOMETHINGs and this is what the inner comprehension does. It looks like your logic is to check if the drug text appears in the file. We already have the drug, so we can just say:</p> <pre><code>[file for file in file_list if drug in file] </code></pre> <p>This runs through the file list and adds it if the drug appears therein.</p> <p>In Python 2.7 and above, you can use a dictionary comprehension instead of using dict(). In that case it would look like:</p> <pre><code>{drug: [file for file in file_list if drug in file] for drug in drug_list} </code></pre> <p>This is much clearer since all the boiler plate of making 2-tuples and converting can be done away with.</p> <p>Comprehensions are an excellent way of writing code because the tend to be very clear descriptions of what you mean to do. It's worth noting that this is not the most efficient way of building the dictionary though, since it runs through every file for every drug. If the list of files is very long this could be very slow.</p> <p><em>Edit: My first answer was nonsense. As penance, I have made this detailed one.</em></p>