0

Say I have a dictionary as follows:

example_dict = {"foo": 1, "bar": 2}

And I want to do multiple lookups semantically equivalent to:

foo = example_dict["foo"]
bar = example_dict["bar"]

Is there any way of doing multiple lookups at once? The closest I have got is using a list comprehension or a generator expression, like:

foo, bar = [example_dict[key] for key in ["foo", "bar"]]
foo, bar = (example_dict[key] for key in ["foo", "bar"])

Ideally what I'd like to do is something like:

foo, bar = example_dict.getmany(["foo", "bar"])

Or even:

foo, bar = example_dict["foo", "bar"]

In a similar way to what you would do with a list or tuple:

foo, bar = "foo", "bar"

Obviously I could define my own function to do this by returning the list comprehension or generator expression above. Or I could create my own dictionary class which if given an iterable to look up, does a lookup per key and returns an iterable. In other data structures (i.e. not a hash), looking up several keys at once feels like it could theoretically provide better performance than many individual lookups. Is there any way to do this?

4

2 回答 2

3

you could use map, i think, though i'm not sure it is really any easier:

In [112]: example_dict = {"foo": 1, "bar": 2}
In [113]: map(example_dict.__getitem__, ['foo', 'bar'])
[0x1,
 0x2]

However, there's not really even theoretically any way to get a speedup from this... each lookup is already more or less constant time (it's a hash lookup) so there's not really an opportunity for collating lookups to have any speedup....

于 2013-11-12T19:44:31.323 回答
0

This question sounds like it is coming from a place of premature optimization, but for the sake of this answer I'll assume the premature bit is not true.

The short answer is that there is no way to do this with stock Python dictionaries. The longer answer is that if there are lookup patterns that are common, you can exploit those to limit the number of lookups. For example, if you always look up "foo" and then "bar" you can instead use a compound key -- perhaps the tuple ("foo", "bar") -- and store the values in a tuple.

The code to store the values would look like

d["foo", "bar"] = (42, 47)

The code to retrieve the values would be so

foo_value, bar_value = d["foo", "bar"]
于 2013-11-12T22:24:05.597 回答