0

Is there a better way of doing this in python 3:

point, edges = edges_per_point.popitem()
edge = edges[0]
if len(edges) > 1:
   edges_per_point[point] = edges[1:] 

I wish to begin with any edge in the dict while also removing it from the dictionary. I also which the list to be removed when it becomes empty.

juliomalegria
  • 24,229
  • 14
  • 73
  • 89
Baz
  • 12,713
  • 38
  • 145
  • 268

3 Answers3

1

Not sure if it is better, but slightly different:

point, edges = edges_per_point.popitem()
if len(edges) > 1:
   edge = edges_per_point[point].pop(0)
else:
   edge = edges[0] 
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
1

If I understood your question right and shamelessly coping one of the deleting-during-iteration way of Lennart Regebro.

I'll do it like this:

edge_list = []
delete_these = []
for point, edges in edges_per_point.items():
    edge_list.append(edges.pop(0))
    if edges:
        edges_per_point[point] = edges
    else:
        delete_these.append(point)

for point in delete_these:
    del edges_per_point[point]
Community
  • 1
  • 1
Rik Poggi
  • 28,332
  • 6
  • 65
  • 82
1

Yes, and no. The main problem is this line:

point, edges = edges_per_point.popitem()

This will remove one item from the dictionary and return it. But which item? Well, you don't know. It's completely arbitrary. Is that really you intention?

The code only makes sense in a loop, where you do this for all items in the dictionary. And then it's better to do this:

for point, edges in edges_per_point.items():
    edge = edges.pop(0)

The pop(0) will remove the first item from the edges list, and put it into the edge variable.

So the above two lines are the answer of a better way to do what you asked for, although it doesn't exactly replace your four lines of code, be cause those four lines make no sense.

Lennart Regebro
  • 167,292
  • 41
  • 224
  • 251