Is there a dictionary-like datastructure that woul

2019-07-09 10:12发布

问题:

I need a structure for my little Python program to save a list of max 500 names with one number each. The names would be unique, but the numbers would repeat (often). I first thought of a dictionary, but I also need to be able to search for the numbers, for instance I would need to change all 2 to 3. What would you recommend?

I am new to Python, so I am sure I overlooked a simple solution.

("Spiderman",1)
("Dr. House",2)
("Jon Skeet",1)

回答1:

You can use a dict, and search by value like so:

names = {"Spiderman":1, "Dr. House":2, "Jon Skeet":1}

resulting_keys = [k for k, v in names.iteritems() if v == 1]
# returns ['Spiderman', 'Jon Skeet']

Then you can do something like:

 names.update(dict((k,names[k] + 1) for k in resulting_keys))

Which will now update names to:

{'Jon Skeet': 2, 'Dr. House': 2, 'Spiderman': 2}


回答2:

Dictionary would work. If you need to change the stored values:

>>> d = {"SpiderMan":1, "Dr.House":2, "Jon Skeet":1}
>>> for k,v in d.items():
...     if v == 1:
...         d[k] = v+1
...         
...     
... 
>>> d
{'SpiderMan': 2, 'Dr.House': 2, 'Jon Skeet': 2}

It's going to be a linear search (O(n)). Do you need better than that?