简体   繁体   中英

Saving a key from a dictionary without value

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?

To make a random choice from some values, use random.choice . You want to choose from the keys of the dictionary, so that's exactly what you pass in:

random.choice(wGraph.keys())

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM