Question: I am representing a weighted graph as a dictionary where the key represents a vertex and the following lists represent the edges incident on the vertex (first number weight of edge and second number adjacent vertex):

```
wGraph = { 1 : [[2, 2],[3, 4],[3, 3]],
       3 : [[3, 2],[5, 4],[7, 5]],
       2 : [[2, 1],[4, 4],[3, 6]],
       4 : [[3, 1],[4, 2],[1, 6],[5, 3]],
       6 : [[3, 2],[1, 4],[8, 5]],
       5 : [[7, 3],[8, 6],[9, 7]],
       7 : [9, 5]}

```

I would like to save a random key without its value from the dictionary to a list called visited.

```
random_num = random.randrange(len(wGraph))

visited = []

```

How can I get the key from the dictionary according to the random number?

Answer: 
The answer depends on the details -- how many keys do you have, are they always numbers 1...max, do you want to revisit keys you've already visited before, are graph nodes added over time or do they stay constant, will you eventually visit all keys or only a small percentage of them, and so on.

One idea: if your keys are always numbered sequentially as in your example, you can just use `random_num + 1`. You already know they are the keys of the dict and you don't have to construct anything special.

Another option is to randomize the key list just once:

```
>>> keys_to_visit = wGraph.keys()
>>> keys_to_visit.shuffle()
>>> first_key_to_visit = keys_to_visit.pop()

```

And just keep calling .pop() whenever you need a new one. This only works if you don't want to revisit nodes and the node list is constant.
```
import random

visited = []

def random_key():
    wGraph = {1: [[2, 2], [3, 4], [3, 3]],
              3: [[3, 2], [5, 4], [7, 5]],
              2: [[2, 1], [4, 4], [3, 6]],
              4: [[3, 1], [4, 2], [1, 6], [5, 3]],
              6: [[3, 2], [1, 4], [8, 5]],
              5: [[7, 3], [8, 6], [9, 7]],
              7: [9, 5]}

    random_key = random.choice(wGraph.keys())

    if random_key not in visited:
        visited.append(random_key)
    print visited

for e in range(7):
    random_key()

```