Check key pattern in dictionary in python

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

How to check if EMP exists in a dictionary using python

  dict1.get("EMP##") ?? 
+7
python dictionary
source share
5 answers

It is not clear what you want to do.

You can scroll through the keys in the dict 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 list comprehension to get all values ​​that match:

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

If you just need to know if the key is suitable, you can use the any() function :

 >>> any(key.startswith("EMP$$") for key in dict1) True 
+22
source share

This approach seems to me contrary to the intent of the dictionary.

A dictionary consists of hash keys that have values ​​associated with them. The advantage of this structure is that it provides a very fast search (of the order of O (1)). Looking through the keys, you deny this benefit.

I would suggest reorganizing your vocabulary.

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

Then finding "EMP $$" is as easy as

 if "EMP$$" in dict1: #etc... 
+6
source share

You need to be more specific with what you want to do. However, assuming the dictionary you gave:

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

If you want to find out if a particular key was present before trying to request it, you can:

 dict1.has_key('EMP$$1') True 

Returns True since dict1 has the key EMP$$1 .

You can also forget about key checking and rely on the default value of dict1.get() :

 dict1.get('EMP$$5',0) 0 

Returns 0 by default dict1 does not have an EMP$$5 key EMP$$5 .

Similarly, you can also use `try / except / structure to search and process missing keys:

 try: dict1['EMP$$5'] except KeyError, e: # Code to deal w key error print 'Trapped key error in dict1 looking for %s' % e 

Other answers to this question are also great, but we need more information to be more accurate.

+2
source share

Unable to match dictionary keys like this. I suggest you reconsider the data structure for this problem. If you need to do this too quickly, you can use something like a suffix tree.

0
source share

You can use the in lines of a statement that checks if an item is on another line. The dict1 iterator returns a list of keys, so you check the "EMP $$" for each dict1.key.

 dict1 = {"EMP$$1": 1, "EMP$$2": 2, "EMP$$3": 3} print(any("EMP$$" in i for i in dict1)) # True # testing for item that doesn't exist print(any("AMP$$" in i for i in dict1)) # False 
0
source share

All Articles