0

Having this dictionary and list:

input_list = {"This_is_House1_Test1": "one", "Also_House2_Mother": "two", "Fefe_House3_Father": "three"}
house_list = [1, 2]

For the example above, I have house_list with 1 and 2, so I just want to maintain on the dictionary the keys containing House1 or House2, and remove the rest of them.

My desired output for the simplified input above is:

{"This_is_House1_Test1": "one", "Also_House2_Mother": "two"}

This is my try with no luck:

for key in list(input_list.keys()):
    for house_id in house_list:
        if "House" + str(house_id) not in key:
                input_list.pop(key)

Thanks in advance!

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
Avión
  • 7,963
  • 11
  • 64
  • 105

3 Answers3

1

One approach is to use regular expressions to verify if and only if one of the values in house_list is in input_list:

import re

input_list = {"This_is_House1_Test1": "one", "Also_House2_Mother": "two",
              "Fefe_House3_Father": "three", "Fefe_House13_Father": "three",
              "Fefe_House14_Father": "three", "Fefe_House24_Father": "three"}

house_list = [1, 2, 13]

house_numbers = "|".join(f"{i}" for i in sorted(house_list, reverse=True))
pat = re.compile(rf"""(House{house_numbers})  # the house patterns
                      \D # not another digit""", re.VERBOSE)

res = {key: value for key, value in input_list.items() if pat.search(key)}
print(res)

Output

{'This_is_House1_Test1': 'one', 'Also_House2_Mother': 'two', 'Fefe_House13_Father': 'three'}

As it can be seen only 1, 2, 13 were match not 3, 14, 24.

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
0

text2int is a function i got from this post: Is there a way to convert number words to Integers?

A one liner would be like this:

{k:v for k, v in input_list.items() if text2int(v) in house_list}
eh329
  • 94
  • 10
  • I did actually. Why do you think i posted it? – eh329 Oct 15 '21 at 12:29
  • Hmm, this is an interesting approach actually. The OP didn't indicate this, but let's see if the dict values are guaranteed to be the English text of the house number. – jarmod Oct 15 '21 at 12:37
  • I ran the for loop after i ran the dict comprehension. I think that is why i did not see the error. – eh329 Oct 15 '21 at 12:42
0

You can use regular expression matching to extract the maximal house numbers from the text, as follows:

import re

input_list = {
    "This_is_House1_Test1": "one",
    "aaa_House11111_aaa": "xxx",
    "Also_House2_Mother": "two",
    "Fefe_House3_Father": "three"
}

house_list = [1, 2]

keys = []
items = {}

for key in input_list.keys():
    result = re.search(r'House(\d+)', key)
    if result and int(result.group(1)) in house_list:
        keys.append(key)
        items[key] = input_list[key]

print("Keys:", keys)
print("Items:", items)

The output is:

Keys: ['This_is_House1_Test1', 'Also_House2_Mother']
Items: {'This_is_House1_Test1': 'one', 'Also_House2_Mother': 'two'}
jarmod
  • 71,565
  • 16
  • 115
  • 122