Filter list of dicts by highest value of dict and taking reversed values into account
<p>Let's say i have data looking like this:</p>

<pre><code>filter_data = [
    {'sender_id': 1, 'receiver_id': 2, 'order': 1},
    {'sender_id': 2, 'receiver_id': 1, 'order': 3},
    {'sender_id': 3, 'receiver_id': 2, 'order': 5},
    {'sender_id': 2, 'receiver_id': 3, 'order': 2},
]

# there must be a better way to get max elements by reversed keys
# in list of dicts, but I think this whole another question
# so for now let this be this way. 
def get_data():
    qs_data = []
    for data in filter_data:
        for cmp_data in filter_data:
            if data['sender_id'] == cmp_data['receiver_id'] and\
                    data['receiver_id'] == cmp_data['sender_id']:
                if data['order'] &gt; cmp_data['order']:
                    d = data
                else:
                    d = cmp_data
                if d not in qs_data:
                    qs_data.append(d)
    return qs_data
</code></pre>

<p>and desired output will be</p>

<pre><code>[{'order': 3, 'receiver_id': 1, 'sender_id': 2},
 {'order': 5, 'receiver_id': 2, 'sender_id': 3}]
</code></pre>

<p>What my code does it filters <code>filter_data</code> so I will get list of items with highest value of <code>order</code> for <code>sender_id</code> and <code>receiver_id</code> but for me <code>receiver_id=1, sender_id=2</code> is same as <code>sender_id=1, receiver_id=2</code></p>

<p>So my question is is there more pythonic/faster way to do this? Or may be can someone point to direction of improvement.</p>

<p><strong>P.S.</strong> I would much appreciate if someone can come up with understandable title. Sorry for my bad English.</p>

<p>You can use a dictionary, mapping a <code>frozenset</code> of sender and receiver ID (so order does not matter) to the item with the currently highest order.</p>

<pre><code>result = {}
for item in filter_data:
    key = frozenset([item["sender_id"], item["receiver_id"]])
    if key not in result or result[key]["order"] &lt; item["order"]:
        result[key] = item
</code></pre>

<p>Then, just extract the <code>values()</code> from the dictionary to get <code>[{'order': 3, 'receiver_id': 1, 'sender_id': 2}, {'order': 5, 'receiver_id': 2, 'sender_id': 3}]</code></p>

<p>Or collect all the items, grouped by sender/receiver pair, and use a list comprehension with <code>max</code> to get those with the highest orders:</p>

<pre><code>result = collections.defaultdict(list)
for item in filter_data:
    key = frozenset([item["sender_id"], item["receiver_id"]])
    result[key].append(item)
max_values = [max(lst, key=lambda x: x["order"]) for lst in result.values()]
</code></pre>

python