Skip to content
Advertisement

How to generate a dictionary of lists containing all possible additive and subtractive combinations of a few lists

Say for instance I have a dictionary with string names as keys, and lists as values:

dict = {}
dict['L1'] = ['a', 'b', 'c', 'd']
dict['L2'] = ['d', 'e', 'f']

I want to generate a new dictionary with keys corresponding to lists that are all the additive or subtractive combinations of the sublists. So this should be the result if we print each sublist in the new dictionary.

print(newdict['L1'])
a b c d
print(newdict['L1 not L2'])
a b c
print(newdict['L1 or L2'])
a b c d e f 
print(newdict['L2'])
d e f
print(newdict['L2 not L1'])
e f

I don’t know what the most efficient way to code the keys is and what the best way to determine the combinations is but the actual adding or subtracting of lists is easy.

Advertisement

Answer

It seems like you want to do set operations, you can do that with python sets:

d = {}   # or d = dict()
d['L1'] = ['a', 'b', 'c', 'd']
d['L2'] = ['d', 'e', 'f']

s1 = set(d['L1'])
s2 = set(d['L2'])

print(s1.union(s2))
# {'a', 'b', 'c', 'd', 'e', 'f'}
print(s1.symmetric_difference(s2))
# {'a', 'b', 'c', 'e', 'f'}
print(s1.intersection(s2))
# {'d'}
print(s1.difference(s2))
# {'a', 'b', 'c'}
print(s2.difference(s1))
# {'e', 'f'}

Side note: When you call your dictionary dict, it overwrites the built-in dict object, you usually don’t want to do that

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement