Newbie question: eliminating entries in dict

Peter Otten __peter__ at web.de
Tue Nov 25 20:25:00 EST 2003


sean wrote:

> I have two dictionaries.
> 
> a = {'a1': 1, 'a2': 5, 'a3': 2, 'a4': 7}
> b = {'something*a4': 1, 'something*something': 1,
> 'somethingelse*somethingelse': 1, 'something*a1: 1}
> 
> What would be an efficient way of eliminating all entries in b which
> contain an entry from a.
> 
> Such that the result would be
> 
> c = ['something*something', 'somethingelse*somethingelse']
> 
> or better still
> c = {'something*something': 1, 'something*something': 1}
> 
> I tried a few different approaches, but they seem very long and
> unnecessary. Also searched the mailing list archives and newsgroups and
> could not come up with anything.
> 
> I know that I will need to compare the .split("*", 1)[1] part of b with
> those from a, but am not sure
> how to implement it.
> 
> Thanks in advance for any help

>>> dict([(k,v) for k, v in b.iteritems() if k.split("*", 1)[1] not in a])
{'something*something': 1, 'somethingelse*somethingelse': 1}

Two newbie collegues? If you really want to learn something in the process,
a homemade for-loop beats that list comprehension thingy copied from usenet
anytime :-)


Peter




More information about the Python-list mailing list