Home > Back-end >  Are all elements in at least 1 nested list of dictionary present in a string
Are all elements in at least 1 nested list of dictionary present in a string

Time:08-30

string = 'christmas is upon us and my father is the greatest of all time and i will celebrate his greatness sad to hear she left'


dict = {
'group1': [['i am a boy','my name is joe','i live in a city'], ['my name is sam','i go to school'],
'group2': ['i a stranger', 'my present sister','i love people'], ['my father is here'],['i go to the village', 'i receive a scholarship'],
'group3': ['i live in the city', 'my wille at salmon today','i have an easy ride'],['my father is the greatest', 'sad to hear she left'],['today is her birth day', 'i will eat the rice','tomorrow is her day']]
}

Given the dictionary with list of values, I'm trying to return the key for which all the elements in a single list within a group are present in the string. for example, looking at the string above, 'my father is the greatest and sad to hear she left' are all present in the 2nd list in group 3. so group 3 should be returned. Again all elements in a list within a group should be present in the string to return the group.

my attempt below:

for key, value in dict.items():
   if True in [all(x in string for x in value[i] for i , sublist in enumerate(value)]:
       print(key)

CodePudding user response:

You can use all() built-in function:

s = "christmas is upon us and my father is the greatest of all time and i will celebrate his greatness sad to hear she left"

dct = {
    "group1": [
        ["i am a boy", "my name is joe", "i live in a city"],
        ["my name is sam", "i go to school"],
    ],
    "group2": [
        ["i a stranger", "my present sister", "i love people"],
        ["my father is here"],
        ["i go to the village", "i receive a scholarship"],
    ],
    "group3": [
        [
            "i live in the city",
            "my wille at salmon today",
            "i have an easy ride",
        ],
        ["my father is the greatest", "sad to hear she left"],
        [
            "today is her birth day",
            "i will eat the rice",
            "tomorrow is her day",
        ],
    ],
}


out = []
for k, v in dct.items():
    for lst in v:
        if all(item in s for item in lst):
            out.append(k)

print(out)

Prints:

['group3']
  • Related