본문 바로가기

프로그램언어/python

[Python] Why You Will Care: Dictionary Interfaces


Why You Will Care: Dictionary Interfaces
Besides being a convenient way to store information by key in your programs, some
Python extensions also present interfaces that look and work the same as dictionaries.
For instance, Python's interface to dbm access-by-key files looks much like a dictionary
that must be opened; strings are stored and fetched using key indexes:

import anydbm
file = anydbm.open("filename") # link to external file
file['key'] = 'data' # store data by key
data = file['key'] # fetch data by key


Later, we'll see that we can store entire Python objects this way too, if we replace
"anydbm" in the above with "shelve" (shelves are access-by-key databases of persistent
Python objects). For Internet work, Python's CGI script support also presents a
dictionary-like interface; a call to cgi.FieldStorage yields a dictionary-like object, with
one entry per input field on the client's web page:

import cgi
form = cgi.FieldStorage() # parse form data (stdin, environ)
if form.has_key('name'):
showReply('Hello, ' + form['name'].value)


All of these (and dictionaries) are instances of mappings. More on CGI scripts in
Chapter 9, Common Tasks in Python.

'프로그램언어 > python' 카테고리의 다른 글

[Python] Modules 사용에 대한 용어 정의  (0) 2010.05.05
[Python] Class Operator Overloading  (0) 2010.05.02
[Python] Built-in Objects Preview  (0) 2010.05.01
[Python] Environment Variables Setting  (0) 2010.05.01
Chap01  (0) 2008.07.24