Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for a key pattern in a dictionary in python

    dict1=({"EMP$$1":1,"EMP$$2":2,"EMP$$3":3})

How to check if EMP exists in the dictionary using python

   dict1.get("EMP##") ??
like image 215
Rajeev Avatar asked Sep 17 '10 13:09

Rajeev


2 Answers

It's not entirely clear what you want to do.

You can loop through the keys in the dict selecting keys using the startswith() method:

>>> for key in dict1:
...     if key.startswith("EMP$$"):
...         print "Found",key
...
Found EMP$$1
Found EMP$$2
Found EMP$$3

You can use a list comprehension to get all the values that match:

>>> [value for key,value in dict1.items() if key.startswith("EMP$$")]
[1, 2, 3]

If you just want to know if a key matches you could use the any() function:

>>> any(key.startswith("EMP$$") for key in dict1)
True
like image 72
Dave Webb Avatar answered Oct 24 '22 05:10

Dave Webb


This approach strikes me as contrary to the intent of a dictionary.

A dictionary is made up of hash keys which have had values associated with them. The benefit of this structure is that it provides very fast lookups (on the order of O(1)). By searching through the keys, you're negating that benefit.

I would suggest reorganizing your dictionary.

dict1 = {"EMP$$": {"1": 1, "2": 2, "3": 3} }

Then, finding "EMP$$" is as simple as

if "EMP$$" in dict1:
    #etc...
like image 39
Tim W. Avatar answered Oct 24 '22 04:10

Tim W.