grab dict keys/values without iterating ?!

Ben Finney ben+python at
Wed Dec 11 04:24:30 CET 2013

Tamer Higazi <tameritoke2 at> writes:

> Is there a way to get dict by search terms without iterating the
> entire dictionary ?!

(A language note: you may be unaware that “?!” does not connote a simple
question, but outrage or incredulity or some other indignant expression.
This implies not a polite query, but more a harsh demand for the other
person to explain.

I think your questions will communicate better punctuated simply with

> I want to grab the dict's key and values started with 'Ar'...

    surnames_by_givenname = {
            "Amanda": "Power",
            "Amaly": "Higgens",
            "Joseph": "White",
            "Arlington": "Black",
            "Arnold": "Schwarzenegger",
    items_whose_keys_start_with_Ar = [
            (key, value)
            for (key, value) in surnames_by_givenname.items()
            if key.startswith("Ar")]

> I could make an iterator and look if it's inside.
> I wasn't able to find it, but I am asking myself if dict has a builtin
> method to get me these key/values on the fly.

Not a method on the dict, but a method on the string and a list
comprehension (or, if you prefer, use a generator expression or dict
comprehension, etc.).

> Why do I ask you?! I am working with the ZODB Database, where I make
> use of a PersistentDict and PersistentList, and I want

I'll be interested to know the rest of that paragraph, to know whether
the above list comprehension meets your constraints.

 \     “I was in the first submarine. Instead of a periscope, they had |
  `\               a kaleidoscope. ‘We're surrounded.’” —Steven Wright |
_o__)                                                                  |
Ben Finney

More information about the Python-list mailing list