1

Here is what I currently have:

from collections import defaultdict

output = [{'MPID': 'A', 'CLIENTNAME': 'AAA'},
          {'MPID': 'C', 'CLIENTNAME': 'BBB'},
          {'MPID': 'C1', 'CLIENTNAME': 'CCC'},
          {'MPID': 'C2', 'CLIENTNAME': 'CCC'},
          {'MPID': 'C3', 'CLIENTNAME': 'CCC'}]

d = defaultdict(list)

for item in output:
    d[item['CLIENTNAME']].append(item['MPID'])

final = [{'CLIENTNAME': k, 'MPID': v} for k, v in d.items()]
print final

This output merges the MPID values of matching CLIENTNAMES.

Output:

[{'MPID': ['A'], 'CLIENTNAME': 'AAA'}, 
 {'MPID': ['C'], 'CLIENTNAME': 'BBB'}, 
 {'MPID': ['C1', 'C2', 'C3'], 'CLIENTNAME': 'CCC'}]

What I am trying to do now is format a string with all permutations of each MPID, but ONLY if the dictionary contains more than 1 MPID. (in this example, only CCC has more than 1 MPID).

Here is the query I am formatting:

query = '''x = '{}' and y = '{}' union 
           x = '{}' and y = '{}';'''

This query needs to compare all MPIDS against one another. The desired output would be:

'''x = 'C1' and y = 'C2' union 
   x = 'C2' and y = 'C1';'''

'''x = 'C2' and y = 'C3' union 
   x = 'C3' and y = 'C2';'''

'''x = 'C1' and y = 'C3' union 
   x = 'C3' and y = 'C1';'''

As you can see, X and Y values swap places in the second line of the string.

What would be an efficient way of going about this part?

Thanks.

1 Answer 1

1

You can use combinations from itertools

from itertools import combinations

combos = list(combinations(final[2]['MPID'], 2))
combos.sort(key=lambda x: x[1])
for combo in combos:
    a, b = combo
    print '''x = '{}' and y = '{}' union 
               x = '{}' and y = '{}';'''.format(a, b, b, a)

This prints:

x = 'C1' and y = 'C2' union 
               x = 'C2' and y = 'C1';
x = 'C1' and y = 'C3' union 
               x = 'C3' and y = 'C1';
x = 'C2' and y = 'C3' union 
               x = 'C3' and y = 'C2';

You may need to adjust the sort key if that order matters to you.

Sign up to request clarification or add additional context in comments.

5 Comments

Hmm, this isn't doing anything. If I print out combos after you define it, it's an empty list.
is final[2]['MPID'] the correct target for how you have it?
That was just an example output. It can be different. The 3rd one in the output isn't always the one that has multiple values. It should be dynamic.
Right, I mean you could loop over it and do this but I just wanted to show you how you would generally go about it.
If you are having trouble getting my example to run, you can see it running at: repl.it/repls/VastMistyProcess. I added a loop there. Nothing will print if there are no combinations to work with.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.