I'm working with a dictionary for an anagram program in Python. The keys are tuples of sorted letters, and the values are arrays of the possible words with those letters:
wordlist = {
('d', 'g', 'o'): ['dog', 'god'],
('a', 'c', 't'): ['act', 'cat'],
('a', 's', 't'): ['sat', 'tas'],
}
I am using regex to filter the list down. So given r't$'
as a filter the final result should be:
filtered_list = {
('a', 'c', 't'): ['act', 'cat'],
('a', 's', 't'): ['sat'],
}
So far I've gotten it down to two steps. First, keep all of the words that match the expression:
tmp = {k: [w for w in v if re.search(r't$', w)] for k, v in wordlist.items()}
This leaves me with empty lists:
{
('d', 'g', 'o'): [],
('a', 'c', 't'): ['act', 'cat'],
('a', 's', 't'): ['sat'],
}
Then I need a second pass to get rid of the empty lists:
filtered_list = {k: v for k, v in tmp.items() if v}
I'm sure there is a way to do these in one step, but I haven't figured it out yet. Is there a way to combine them? Or a better way to do this in general?
Note that the restriction with keys in Python dictionary is only immutable data types can be used as keys, which means we cannot use a dictionary of list as a key . But the same can be done very wisely with values in dictionary.
Method 1: Using += sign on a key with an empty value In this method, we will use the += operator to append a list into the dictionary, for this we will take a dictionary and then add elements as a list into the dictionary.
To convert a list to a dictionary using the same values, you can use the dict. fromkeys() method. To convert two lists into one dictionary, you can use the Python zip() function. The dictionary comprehension lets you create a new dictionary based on the values of a list.
Doing this in two steps is fine, and probably good for readability.
But to answer your question, here's a one-liner (broken into multiple lines, for readability). It uses a generator expression for generating the pairs from the first step.
{
k:v for k, v in
(
(kk, [w for w in vv if re.search(r't$', w)])
for kk, vv in wordlist.items()
)
if v
}
=> {('a', 'c', 't'): ['act', 'cat'], ('a', 's', 't'): ['sat']}
For a one-liner, something like this?
A = {k:[w for w in v if re.search(r't$', w)] for k,v in wordlist.items() if any(re.search(r't$', w) for w in v)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With