Home > Back-end >  Looping a dictonary and keep keys with a conrete value of list
Looping a dictonary and keep keys with a conrete value of list

Time:10-15

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!

CodePudding user response:

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.

CodePudding user response:

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}

CodePudding user response:

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'}
  • Related