Search code examples
pythonsortingdictionarytuplesnetworkx

accessing the value of a dictionary from a tuple


I am working with networkx and I need to sort the edges based on the value of the weights. the edges come in the form of a list of tuples with the weight as a dictionary, the third element of the tuple:

G.edges = [(u, v, {'weight' = value})]  

I am trying to use

sorted(G.edges(data = True), key= lambda x: x[2].values())

but I am getting the error:

TypeError: '<' not supported between instances of 'dict_values' and 'dict_values'.  

Could you pleas help me with this.
Thanks


Solution

  • I would think you'd want the actual value not all the dict_values.

    sorted(G.edges(data = True), key=lambda x: x[2].get("weight", 0))
    

    The relevance of the second argument to get is that by default dict.get returns None for keys that don't exist in the dictionary, so you'd risk (maybe) raising an exception for indexing with a NoneType. This simply sets the weight sort value to 0 in those cases.