I have an increasing number of n_term dictionaries, where the values of E need to be combined in a specific way. The dictionaries have the form:
one_terms = {'i': {'E':1},
'j': {'E':2},
...
'n': {'E':some_int}}
two_terms = {'i:j': {'E':12},
'i:k': {'E':13},
...
'm:n': {'E':some_int}}
three_terms = {'i:j:k': {'E':111},
'i:j:l': {'E':112},
...
'm:n:o': {'E':some_int}}
The numbers inside are placeholders. In reality these numbers come from computationally expensive calculations. The number of dictionaries holding n-terms (ijkl...n) can also become large. For instance, this can go up to a fifty_term dictionary.
The intention is to combine all the corresponding terms of a n_term dictionary and append that value to the appropriate dictionary. An example explains this better:
the task is relatively simple for a low number of terms (2 or 3), and can be done without an invoking combinations. For example, for the two_term dictionary:
for key, value in two_terms.items():
i = one_terms[str(key).split(':')[0]]['E']
j = one_terms[str(key).split(':')[1]]['E']
ij = 0 -i -j
two_terms[key]['new_value'] = ij
Gives the solution I desire. And for the three_terms dictionary.
for key, value in three_terms.items():
i = one_terms[str(key).split(':')[0]]['E']
j = one_terms[str(key).split(':')[1]]['E']
k = one_terms[str(key).split(':')[2]]['E']
ij = two_terms[(str(key).split(':')[0] + ':' + two_terms[(str(key).split(':')[1])]['E']
ik = two_terms[(str(key).split(':')[0] + ':' + two_terms[(str(key).split(':')[2])]['E']
jk = two_terms[(str(key).split(':')[1] + ':' + two_terms[(str(key).split(':')[2])]['E']
ijk = 0 -ij -ik -jk -i -j -k
three_terms[key]['new_value'] = ijk
Also gives the desired solution. Note that I have used the split() function to go through the different key combinations (ij, ik, etc).
However, for an increasing number of n_terms this method becomes impractical. I need an iterative solution.
My attempt.
I have attempted to use the itertools.combinations library so that I can iteratively go through all combinations.
for C in range(1, len(dictionary):
for S in itertools.combinations(dictionary, C):
However, this simply provides a tuple which becomes difficult to manipulate into something of the form
n = n_terms[(str(key).split(':')[A] + ':' +\
str(key).split(':')[B] + ':' +\
...
str(key).split(':')[Z])]['E']
Where A, B,...Z would be combinations.
In the two_term case, the solution might take the form:
for key, value in two_term.items():
n_list
for i in range (0, 2):
n_list.append(one_terms[str(key).split(':')[i]])
two_body[key]['E'] = sum(n_list)
Though I am struggling to extend this method.