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)', 'b
Solution 1:
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()}
Solution 2:
temp_dict = d
forkey, 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.
Post a Comment for "How To Iterate Through Dict Values Containing Lists And Remove Items?"