Finding all groups an item is a member of

I want to be able to find all members of a group and all groups that an item is a member of…

The first part of this seems easily solved using a dict:

groups = {
          'Group1': [ 'Member A', 'Member B', 'Member C' ],
          'Group2': [ 'Member A', 'Member D', 'Member E' ],
          'Group3': [ 'Member C', 'Member E', 'Member F' ]

But do I have to iterate through all the Groups to find which one(s) ‘Member C’ is a member of, or is the answer to be found somewhere in the use of sets? What’s the quickest way of doing this?

I think your fastest way to do the second part is to use the python set data structure:

I’d rewrite your table like this:

groups = {
          'Group1': set('Member A', 'Member B', 'Member C' ),
          'Group2': set('Member A', 'Member D', 'Member E' ),
          'Group3': set('Member C', 'Member E', 'Member F' )

assert 'Member A' in groups['Group1']

That last line is a quick test to show you how to use it. You just use the in syntax and it should be really fast to do it this way.

Thanks Zed, I’m still getting to grips with sets but I had a feeling there might be an answer in them.

A couple of things:

First, I think the syntax in your example was a little incorrect as set() seems to expect an iterable.

groups = {
          'Group1': set(['Member A', 'Member B', 'Member C']),
          'Group2': set(['Member A', 'Member D', 'Member E']),
          'Group3': set(['Member C', 'Member E', 'Member F'])

Second, is there a way to search the entire ‘groups’ dict to find all groups that ‘Member A’ belongs to or am I still stuck with iterating through all of the keys one at a time?

Yes, that’s right, it takes 1 argument and can’t translate multiples.

I think if you don’t want to iterate then you’re going to have to learn the map/reduce family of functions:

Keep in mind that these are just doing the loop for you, but it might work more the way you’re thinking. The idea is you hand the data to successive filter functions and operations to get a final new data structure with what you want.