Home > Back-end >  Map values from dictionary's list to a string in Python
Map values from dictionary's list to a string in Python

Time:12-13

I am working on some sentence formation like this:

sentence = "PERSON is ADJECTIVE"
dictionary = {"PERSON": ["Alice", "Bob", "Carol"], "ADJECTIVE": ["cute", "intelligent"]}

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

Alice is cute
Alice is intelligent
Bob is cute
Bob is intelligent
Carol is cute
Carol is intelligent

Can we also make this scale up for longer sentences?

Example:

sentence = PERSON is ADJECTIVE and is from COUNTRY 
dictionary = {"PERSON": ["Alice", "Bob", "Carol"], "ADJECTIVE": ["cute", "intelligent"], "COUNTRY": ["USA", "Japan", "China", "India"]}

This again provides all possible combinations

CodePudding user response:

You can do this,

dictionary = {"PERSON": ["Alice", "Bob", "Carol"], "ADJECTIVE": ["cute", "intelligent"]}

for i in dictionary["PERSON"]:
    for j in dictionary["ADJECTIVE"]:
        print(f"{i} is {j}")

Output:

Alice is cute
Alice is intelligent
Bob is cute
Bob is intelligent
Carol is cute
Carol is intelligent

Here in the outer loop iterate through each of the elements of the list having key PERSON and the inner loop iterate through the element of the list having key ADJECTIVE. being inside the outer loop the inner loop repeat itself for each element of the first list/list with key PERSON.

CodePudding user response:

for x in sentence: for y in dictionary: print(x, y)

something like this?

  • Related