简体   繁体   中英

Map values from dictionary's list to a string in Python

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

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 .

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

something like this?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM