Reputation: 1332
In order to remove attributes from a networkx graph I have the following code:
for (n1,n2) in graph.edges(data=False):
for att in att_list:
graph[n1][n2].pop(att, None)
Is there a more pythonic way to do so?
Upvotes: 2
Views: 5170
Reputation: 23887
If you only want to delete a few attributes in some list, say att_list
for n1, n2, d in graph.edges(data=True):
for att in att_list:
d.pop(att, None)
Or you can replace the last line with if att in d: del d[att]
if it bothers you that pop
returns something that you aren't using. The improvement compared to your code is that by having data=True
I get d
immediately, rather than having to reference graph[n1][n1]
later.
See Removing multiple keys from a dictionary safely for how to remove multiple keys from a dictionary (which is what d
is). Fundamentally that's what your problem reduces to once you've got d
.
Alternately, if you want to clear all of the attributes, then note that if we set data=True
, then graph.edges
also returns a dictionary with the attributes. Clear this dictionary.
for (n1, n2, d) in graph.edges(data=True):
d.clear()
Here's a complete example
import networkx as nx
G=nx.Graph()
G.add_edge(1,2,weight=2)
G.edge[1][2]
> {'weight': 5}
for (n1, n2, d) in G.edges(data=True):
d.clear()
G.edge[1][2]
> {}
#just to check the edge in the opposite order
G.edge[2][1]
> {}
Upvotes: 3