Evan Emolo
Evan Emolo

Reputation: 1670

How to iterate through dict values containing lists and remove items?

Python novice here. I have a dictionary of lists, like so:

d = {
  1: ['foo', 'foo(1)', 'bar', 'bar(1)'],
  2: ['foobaz', 'foobaz(1)', 'apple', 'apple(1)'],
  3: ['oz', 'oz(1)', 'boo', 'boo(1)']
}

I am trying to figure out how to loop through the keys of the dictionary and the corresponding list values and remove all strings in each in list with a parantheses tail. So far this is what I have:

for key in keys:
    for word in d[key]...: # what else needs to go here?
        regex = re.compile('\w+\([0-9]\)')
        re.sub(regex, '', word)  # Should this be a ".pop()" from list instead?

I would like to do this with a list comprehension, but as I said, I can't find much information on looping through dict keys and corresponding dict value of lists. What's the most efficient way of setting this up?

Upvotes: 3

Views: 8470

Answers (3)

Aya
Aya

Reputation: 42080

Alternatively, you can do it without rebuilding the dictionary, which may be preferable if it's huge...

for k, v in d.iteritems():
   d[k] = filter(lambda x: not x.endswith(')'), v)

Upvotes: 1

scottydelta
scottydelta

Reputation: 1806

temp_dict = d
for key, value is temp_dict:
    for elem in value:
        if temp_dict[key][elem].find(")")!=-1:
            d[key].remove[elem]

you can't edit a list while iterating over it, so you create a copy of your list as temp_list and if you find parenthesis tail in it, you delete corresponding element from your original list.

Upvotes: 1

eumiro
eumiro

Reputation: 213075

You can re-build the dictionary, letting only elements without parenthesis through:

d = {k:[elem for elem in v if not elem.endswith(')')] for k,v in d.iteritems()}

Upvotes: 8

Related Questions