Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading