Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paring Down a Dictionary of Lists in Python

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?

like image 485
phraktyl Avatar asked Apr 25 '14 17:04

phraktyl


People also ask

Is it possible to declare a list of dictionary and dictionary of list in Python?

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.

Can you append lists in a dictionary Python?

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.

How do you pass a list into a 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.


2 Answers

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']}
like image 126
shx2 Avatar answered Oct 14 '22 16:10

shx2


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)}
like image 38
ysakamoto Avatar answered Oct 14 '22 18:10

ysakamoto