nimgwfc
nimgwfc

Reputation: 1509

Check if a dictionary value contains a list item

I have a dictionary which has a key (a two digit prefix) and a value (a list of strings). It looks something like this:

prefixes = {
    "AC" : ["england-wales"],
    "OC" : ["england-wales", "wales"],
    "SC" : ["scotland"],
    "NC" : ["northern-ireland"]
}

I am trying to create a list of prefixes in which the value contains a region provided in a list.

The region passed through can be one or more regions, for example:

regions = ['england-wales', 'wales']

So, with the above data I would like to create a new list called prefixes and it will contain all the prefixes where either 'wales' or 'england-wales' is included in the value:

prefix_list = ['AC', 'OC']

Whereas if regions is just equal to 'wales' then:

prefix_list = ['OC']

I have played around with a few things and got this messy solution working:

combo_list = []
prefix_list = []

for r in regions:
    combo_list.append([k for k, v in prefixes.items() if r in v])

for sublist in combo_list:
    for i in sublist:
        prefix_list.append(i)

prefix_list = sorted(set(prefix_list)) #This will remove duplicates for me

I think there must be a better, 'cleaner' way of doing this but can't quite figure it out. Any help is appreciated.

Upvotes: 1

Views: 235

Answers (1)

CDJB
CDJB

Reputation: 14516

You can use any() for this - as a list comprehension:

prefix_list = [k for k, v in prefixes.items() if any(x in v for x in regions)]

Gives us

>>> prefix_list
['AC', 'OC']

Upvotes: 6

Related Questions