Is There A Dictionary-like Datastructure That Would Allow Searches For 'key' And For 'value'
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 thoug
Solution 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}
Solution 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?
Post a Comment for "Is There A Dictionary-like Datastructure That Would Allow Searches For 'key' And For 'value'"