TypeError: '>' not supported between instances of 'dict' and 'dict'

左心房为你撑大大i 提交于 2021-01-29 09:55:01

问题


I'm working with dictionaries and I have the following error

'>' not supported between instances of 'dict' and 'dict'

I know that there are some problems with dictionaries in Python 2.7 and 3.x version.

print("number of nodes %d" % G.number_of_nodes())
print("number of edges %d" % G.number_of_edges())
print("Graph is connected?: %s" % nx.is_connected(G))
print("Number of connected components: %s" % nx.number_connected_components(G))
print("Size of connected componnents: %s" % [len(cc) for cc in nx.connected_components(G)])
print("Network Analysis will be performed on the largest cc from now on") 
largest_cc = max(nx.connected_component_subgraphs(G), key=len) 

dict_communities={}
num_communities=max([y for x,y in largest_cc.nodes(data=True)]).values()[0]
for i in range (1,num_communities+1):
    dict_communities[i] = [x for x,y in largest_cc.nodes(data=True) if y['community']==i]
TypeError                                 Traceback (most recent call last)
<ipython-input-12-fd6e5cb0ddb5> in <module>
      1 dict_communities={}
----> 2 num_communities=max([y for x,y in largest_cc.nodes(data=True)])[0]
      3 for i in range (1,num_communities+1):
      4     dict_communities[i] = [x for x,y in largest_cc.nodes(data=True) if y['community']==i]

TypeError: '>' not supported between instances of 'dict' and 'dict'

回答1:


In networkx, graph.nodes(data=True) returns a list of node_id-dicts tuples with node arguments. But in Python dicts can't be compared (you are trying to compare them when you are calling max function). You should do it with some another way, like extracting the particular argument of each node with code like this:

max([y['some_argument'] for x,y in largest_cc.nodes(data=True)])
           ^
           |
Add it ----+


Here is the example:

We create a random graph and fill 'arg' argument with random numbers:

import networkx as nx
import random

G = nx.gnp_random_graph(10,0.3,directed=True)
for node in G.nodes:
    G.nodes[node]['arg'] = random.randint(1, 10)

Then we are trying to use your code:

[y for x,y in G.nodes(data=True)]

It returns:

[{'arg': 8},
 {'arg': 5},
 {'arg': 9},
 {'arg': 4},
 {'arg': 8},
 {'arg': 6},
 {'arg': 3},
 {'arg': 2},
 {'arg': 8},
 {'arg': 1}]

And you can't compare these dicts with each other.

But if you will specify 'arg' in the list:

[y['arg'] for x,y in G.nodes(data=True)]

It will return:

[8, 1, 5, 3, 10, 5, 7, 10, 1, 2]

And you can pick the largest element (but don't write .values()[0] in the end of the line, it will cause an error):

max([y['arg'] for x,y in G.nodes(data=True)])

10



来源:https://stackoverflow.com/questions/56464957/typeerror-not-supported-between-instances-of-dict-and-dict

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!