# [Tutor] Iterate through dictionary values and remove item

bob gailer bgailer at gmail.com
Thu May 15 13:01:12 CEST 2008

```GTXY20 wrote:
> Hello all,
>
> I have dictionary like the following:
>
> d={(1,23A):[a,b,c,d],  (1,24A):[b,c,d], (2,23A):[a,b], (2,24A):[a,b,c,d]}
>
> I would like to iterate through the dictionary such that if it finds
> the value 'a' in the values of the key that it would remove the value
> 'b' from the values list. In addition if it finds 'a' in the values
> list I would like it to take the first item from the key tuple k[0]
> and and then look through the dictionary for that k[0] value and then
> remove 'b' from its value list even if 'a' is not present in that
> list. So at the end I would like my dictionary to end with:
>
> d={(1,23A):[a,c,d],  (1,24A):[c,d], (2,23A):[a], (2,24A):[a,c,d]}
>
> Initally I did the following:
>
> for k,v in d.items():
> u=k[0]
> b=k[1]
> if 'a' in v:
> for k,v in d.items():
> if k[0] == u:
> for values in v:
> if values == 'b':
> v.remove(values)
>
> However this will be a very big dictionary and it ended up running for
> a very long time - in fact I had to kill the process.
>
> Can anyone suggest an alternate method to do this?
>
> Thanks in advance for any suggestions.
>

d={(1,23A):[a,c,d],  (1,24A):[c,d], (2,23A):[a], (2,24A):[a,c,d]}

That gives a syntax error at the first A.
And the rest of the code lacks indentation.

Your code does not match your specification. You said "... if it finds
the value 'a' in the values of the key...." but you test

if 'a' in v:

Please fix these issues and repost.

--
Bob Gailer
919-636-4239 Chapel Hill, NC

```