Filter a Python dictionary

((u'Valjean', u'MmeDeR'), (u'MmeDeR', u'Valjean'))
((u'Valjean', u'Montparnasse'), (u'Montparnasse', u'Valjean'))
((u'Myriel', u'Count'), (u'Count', u'Myriel'))
((u'Valjean', u'Judge'), (u'Judge', u'Valjean'))
((u'Napoleon', u'Myriel'), (u'Myriel', u'Napoleon'))
((u'Myriel', u'Valjean'), (u'Valjean', u'Myriel'))
((u'Champtercier', u'Myriel'), (u'Myriel', u'Champtercier'))
((u'Myriel', u'OldMan'), (u'OldMan', u'Myriel'))
((u'Valjean', u'Woman1'), (u'Woman1', u'Valjean'))
((u'Valjean', u'Babet'), (u'Babet', u'Valjean'))
((u'MlleBaptistine', u'Valjean'), (u'Valjean', u'MlleBaptistine'))
((u'MmeMagloire', u'Myriel'), (u'Myriel', u'MmeMagloire'))
((u'Valjean', u'Labarre'), (u'Labarre', u'Valjean'))
((u'Valjean', u'Woman2'), (u'Woman2', u'Valjean'))
((u'Myriel', u'Geborand'), (u'Geborand', u'Myriel'))
((u'Valjean', u'Marguerite'), (u'Marguerite', u'Valjean'))
((u'MlleBaptistine', u'MmeMagloire'), (u'MmeMagloire', u'MlleBaptistine'))
((u'Valjean', u'Isabeau'), (u'Isabeau', u'Valjean'))
((u'Valjean', u'Simplice'), (u'Simplice', u'Valjean'))
((u'Valjean', u'Gillenormand'), (u'Gillenormand', u'Valjean'))
((u'Valjean', u'MlleGillenormand'), (u'MlleGillenormand', u'Valjean'))
((u'Myriel', u'Champtercier'), (u'Champtercier', u'Myriel'))
((u'Valjean', u'MmeMagloire'), (u'MmeMagloire', u'Valjean'))
((u'Valjean', u'Fantine'), (u'Fantine', u'Valjean'))
((u'MlleBaptistine', u'Myriel'), (u'Myriel', u'MlleBaptistine'))
((u'Valjean', u'Myriel'), (u'Myriel', u'Valjean'))
((u'Valjean', u'Cosette'), (u'Cosette', u'Valjean'))

I am used to the verbosity of Java. So Python is like a breath of fresh air.
But this Python code stumped me for the better part of two days.

I was trying to filter the keys in the dictionary shown above based on its own values. One of the examples is shown in a different color. So if the key matches a value then that dictionary row with that particular key should be removed. The row with the matching value is untouched.

It is literally one line of Python.

    for v in friends.iteritems():
        print v
    result = [k for k, v in friends.iteritems() if v not in friends.keys()]
    for v in result:
        print v

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: