Skip to content
Advertisement

Mapping values from a dictionary’s list to a string in Python

I am working on some sentence formation like this:

JavaScript

I would now need all possible combinations to form this sentence from the dictionary, like:

JavaScript

The above use case was relatively simple, and it was done with the following code

JavaScript

But can we also make this scale up for longer sentences?

Example:

JavaScript

This should again provide all possible combinations like:

JavaScript

I tried to use https://www.pythonpool.com/python-permutations/ , but the sentence are all are mixed up – but how can we make a few words fixed, like in this example the words "and is from" is fixed

Essentially if any key in the dictionary is equal to the word in the string, then the word should be replaced by the list of values from the dictionary.

Any thoughts would be really helpful.

Advertisement

Answer

I would base my answer off of two building blocks itertools.product and zip.

itertools.product will allow us to get the various combinations of our dictionary list values

zip with the original keys and the combinations above will allow us to create a list of tuples that we can use with replace.

JavaScript

IF you happen to have the ability to control the “sentence” template, and you can do:

JavaScript

Then you can simplify this to:

JavaScript

both should give you the results like:

JavaScript

Note that the order of appearance in the template is not important and both solutions should work with a template of:

JavaScript

or in case 2

JavaScript

Followup:

What happens if there is a chance that the dictionary contains items that are not in the sentence template? At the moment, that is not ideal as the way the sentences are generated with product() assumes that all keys are and we currently would generate duplicates.

The easiest fix for that would be to just ensure that the dictionary only has keys of interest…

In the first case this might do that.

JavaScript

or in the second case:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement