简体   繁体   中英

Finding a key in a dictionary without knowing its full name

I have a dictionary with a key called ev#### where #### is some number that I do not know ahead of time. There is only one of this type of key in the dictionary and no other key starts with ev.

What's the cleanest way to access that key without knowing what the #### is?

You can try this list comprehension: ( ideone )

result = [v for k, v in d.iteritems() if k.startswith('ev')][0]

Or this approach using a generator expression: ( ideone )

result = next(v for k, v in d.iteritems() if k.startswith('ev'))

Note that these will both require a linear scan of the items in the dictionary, unlike an ordinary key-lookup which runs in constant time on average (assuming a good hash function). The generator expression however can stop as soon as it finds the key. The list comprehension will always scan the entire dicitonary.

Store the item in the dictionary without the ev prefix in the first place.

If you also need to access it with the prefix, store it both ways.

If there can be multiple prefixes for a given number, use a second dictionary that stores the actual keys associated with each number as a list or sub-dictionary, and use that to find the available keys in the main dictionary matching the number.

If you can't easily do this when the dictionary is initially created (eg someone else's code is giving you the dict and you can't change it), and you will be doing a lot of lookups of this sort, it is probably worthwhile to iterate over the dict once and make the second dict, or use a dict to cache the lookups, or something of that sort, to avoid iterating the keys each time.

If there is only one such value in the dictionary, I would say it's better to use an approach similar to this:

for k,v in d.iteritems():
    if k.startswith('ev'):
        result = v
        break
else:
    raise KeyError()  # or set to default value

That way you don't have to loop through every value in the dictionary, but only until you find the key, which should speed up the calculation by ~ 2x on average.

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