Home > Mobile >  Pick list elements from inside dictionary
Pick list elements from inside dictionary

Time:08-25

I would like to iterate over the lists inside the dictionary below and return the elements that are not inside both of the lists.

{'ABC-01': ['aaa',
            'bbb',
            'ccc',
            'ddd'],
 'ABC-02': ['aaa',
            'bbb',
            'ccc',
            'eee']}

It would then return something like:

ABC-01 contains ddd
ABC-02 contains eee

I just can't seem to figure it out.

CodePudding user response:

You can use set xor (^ = find all items unique in some set) and then set intersection (& = find all items that overlap between sets) to do this pretty easily.

obj = {'ABC-01': ['aaa',
            'bbb',
            'ccc',
            'ddd'],
       'ABC-02': ['aaa',
            'bbb',
            'ccc',
            'eee']}

unique_items = set()
for key in obj:
    obj[key] = set(obj[key])
    unique_items ^= obj[key]

for key in obj:
    print(key   " contains "   str(obj[key] & unique_items))

Output:

ABC-01 contains {'ddd'}
ABC-02 contains {'eee'}
  • Related