16
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

正規表現を使った辞書キー指定

Posted at

使い方

ありそうでなかったので書いた。メモとして残します。
辞書をrdict型にキャストすれば正規表現もキー値として使えるようになるやつです。
標準辞書型を継承しているので、普通の機能も使えると思います。

>>d = {'#a': 'item1', '#b': 'item2','q#': 'item3'}
>>rd = rdict(d)

>>print rd[".*"]
['item2', 'item1', 'item3']

>>print rd["#.*"]
['item2', 'item1']

>>print rd["#a"]
item1

>>print rd.keys()
['#b', '#a', 'q#']

ソース

rdict.py
#もっといいやり方あれば教えて欲しいです。
import re
class rdict(dict):
	def __getitem__(self, key):
		try:
			return super(rdict, self).__getitem__(key)
		except:
			try:
				ret=[]
				for i in self.keys():
					m= re.match("^"+key+"$",i)
					if m:ret.append( super(rdict, self).__getitem__(m.group(0)) )
			except:raise(KeyError(key))
		return ret

#制限
辞書にキー.*が含まれていると、正規表現.*ではそのキーの値のみを返します。(キー全てにマッチできない)

16
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?