开发者

Python: Access dictionary value inside of tuple and sort quickly by dict value

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 wher开发者_JAVA百科e 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜