views:

167

answers:

1

I know that wasn't clear. Here's what I'm doing specifically. I have my list of dictionaries here:

dict = [{int=0, value=A}, {int=1, value=B}, ... n]

and I want to take them in combinations, so I used itertools and it gave me a tuple (Well, okay it gave me a memory object that I then used enumerate on so I could loop over it and enumerate gave ma tuple):

for (index, tuple) in enumerate(combinations(dict, 2)):

and this is where I have my problem. I want to identify which of the two items in the combination has the bigger 'int' value and which has the smaller value and assign them to variables (I'm actually using more than 2 in the combination so I can't just say if tuple[0]['int'] > tuple[1]['int'] and do the assignment because I'd have to list this out a bunch of times and that's hard to manage).

I was going to assign each 'int' value to a variable, sort it in a list, index the 'int' value in the list by 1, 2, 3, 4, 5 ... etc., then go back and access the dictionary I wanted by the int value and then assign the dictionary to a variable so I knew which was bigger. But I have a big list and lists and variable assignments are resource intensive and this is taking a long time (I had only a little bit of that written and it was taking forever to run).

So I was hoping someone knew a fast way to do this. I actually could list out every possible combination of assignmnets using the if/thens but it's just like 5 pages of if/thens and assignments and is hard to read and manage when I want to change it.

You've probably gathered this, but I"m new at programming. thx

+1  A: 
for (index, tuple) in enumerate(combinations(dict, 2)):
    thesmall = min(tuple, key=lambda d: d['int'])
    thelarge = max(tuple, key=lambda d: d['int'])

If you need more than just min and max, then

    inorder = sorted(tuple, key=lambda d: d['int'])

and there you have all the dicts in order as required.

Alex Martelli
The use of a lambda can be avoided by using `operator.itemgetter`, eg `inorder = sorted(tuple, key=operator.itemgetter('int'))` Although reputedly faster, this is perhaps not of interest to a new programmer, unless the new programmer finds the use of `lambda` confusing or unclear. In that case the new programmer is reminded to `import operator` before using `operator.itemgetter`. Although since the new programmer is using `itertools`, the new programmer likely understands the mechanics of importing :)
intuited