How to sort networkx edgelist by 2 edge attributes

Question:

I want to sort this edgelist by 2 edge attributes descending in value.

df_test = pd.DataFrame({'A':['AXQ00084.1', 'AXQ00134.1', 'AZI75768.1', 'AZI75768.1','AZI75801.1','AZI75801.1'],
                         'B':['AZI75768.1', 'AZI75768.1', 'AXQ00084.1', 'AXQ00134.1','AXQ00106.1','AXQ00107.1'],
                         'X': [607, 272, 595, 323,30,30],
                         'Y':[99.675, 83.23, 97.70, 98.78,97,99]})

g2 = nx.from_pandas_edgelist(df_test, 'A', 'B', edge_attr=['X','Y'])
g2.edges(data=True)
g_dict = sorted(g2.edges(data=True),key= lambda x: x[1][2],reverse=False)

g_dict returns:

[('AXQ00084.1', 'AZI75768.1', {'X': 595, 'Y': 97.7}),
 ('AZI75768.1', 'AXQ00134.1', {'X': 323, 'Y': 98.78}),
 ('AZI75801.1', 'AXQ00106.1', {'X': 30, 'Y': 97.0}),
 ('AZI75801.1', 'AXQ00107.1', {'X': 30, 'Y': 99.0})]

When the desired output is:

 [('AXQ00084.1', 'AZI75768.1', {'X': 595, 'Y': 97.7}),
 ('AZI75768.1', 'AXQ00134.1', {'X': 323, 'Y': 98.78}),
 ('AZI75801.1', 'AXQ00107.1', {'X': 30, 'Y': 99.0}),
 ('AZI75801.1', 'AXQ00106.1', {'X': 30, 'Y': 97.0})]
Asked By: skiventist

||

Answers:

Use a tuple of the dictionary values:

g_dict = sorted(g2.edges(data=True),
                key=lambda x: (x[2]['X'], x[2]['Y']),
                reverse=True)

more generic approach in case you have many keys to handle:

from operator import itemgetter
g_dict = sorted(g2.edges(data=True),
                key=lambda x: itemgetter('X', 'Y')(x[2]),
                reverse=True)

output:

[('AXQ00084.1', 'AZI75768.1', {'X': 595, 'Y': 97.7}),
 ('AZI75768.1', 'AXQ00134.1', {'X': 323, 'Y': 98.78}),
 ('AZI75801.1', 'AXQ00107.1', {'X': 30, 'Y': 99.0}),
 ('AZI75801.1', 'AXQ00106.1', {'X': 30, 'Y': 97.0})]
Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.