开始Python — Dictionary

1、Dictionary语法

l         Dictionary由key/value对(称为项目)组成,key和value之间用“:”分割,项目用“,”分割,所有项目用“{}”包括起来

>>> phonebook = {’Alice’: ‘2341′, ‘Beth’: ‘9102′, ‘Cecil’: ‘3258′}

l         Dictionary的key值必须唯一,否则后者会覆盖前者:

>>> phonebook = {’Alice’: ‘2341′, ‘Alice’: ‘9102′, ‘Cecil’: ‘3258′}

>>> phonebook

{’Alice’: ‘9102′, ‘Cecil’: ‘3258′}

l         使用dict()函数可以从Mapping(如其它的Dictionary)或key/value形式的Sequence创建Dictionary:

>>> items = [('name', 'Gumby'), ('age', 42)]

>>> d = dict(items)

>>> d

{’age’: 42, ‘name’: ‘Gumby’}

l         也可以用keyword参数来创建Dictionary:

>>> d = dict(name=’Gumby’, age=42)

>>> d

{’age’: 42, ‘name’: ‘Gumby’}

 

2、基本Dictionary操作

l         Dictionary支持Sequence的基本操作,但要注意下面几点:

l         key值可以是任何类型,但必须是不可变类型,如整数、浮点数、String、Tuple

l         对项目赋值时,如果key值不存在,会新建项目:

>>> x = {}

>>> x[42] = ‘Foobar’

>>> x

{42: ‘Foobar’}

l         使用in操作符时,是查找key值,而不是value值

 

3、使用Dictionary格式化String

l         转换形式:%(key)type(type是转换类型)

>>> template = ”’<html>

<head><title>%(title)s</title></head>

<body>

<h1>%(title)s</h1>

<p>%(text)s</p>

</body>”’

>>> data = {’title’: ‘My Home Page’, ‘text’: ‘Welcome to my home page!’}

>>> print template % data

<html>

<head><title>My Home Page</title></head>

<body>

<h1>My Home Page</h1>

<p>Welcome to my home page!</p>

</body>

 

4、Dictionary方法

(1) clear:移去Dictionary中所有的元素

>>> d = {’age’: 42, ‘name’: ‘Gumby’}

>>> d

{’age’: 42, ‘name’: ‘Gumby’}

>>> d.clear()

>>> d

{}

l         注意,d.clear()和d = {}结果相同,但含义不同:后者是指向了一个新的空Dictionary

(2) copy:返回具有相同key/value对的新Dictionary(注意value值是共用的)

>>> x = {’username’: ‘admin’, ‘machines’: ['foo', 'bar', 'baz']}

>>> y = x.copy()

>>> y['username'] = ‘mlh’

>>> y['machines'].remove(’bar’)

>>> y

{’username’: ‘mlh’, ‘machines’: ['foo', 'baz']}

>>> x

{’username’: ‘admin’, ‘machines’: ['foo', 'baz']}

l         避免上面问题的方法是对value值也进行拷贝,可以使用copy模块中的deepcopy()函数:

>>> from copy import deepcopy

>>> d = {}

>>> d['names'] = ['Alfred', 'Bertrand']

>>> c = d.copy()

>>> dc = deepcopy(d)

>>> d['names'].append(’Clive’)

>>> c

{’names’: ['Alfred', 'Bertrand', 'Clive']}

>>> dc

{’names’: ['Alfred', 'Bertrand']}

(3) fromkeys:根据给定的key值创建新的Dictionary,缺省value值为None

>>> {}.fromkeys(['name', 'age'])

{’age’: None, ‘name’: None}

l         可以使用Dictionary的Type(后面讲述):dict

>>> dict.fromkeys(['name', 'age'])

{’age’: None, ‘name’: None}

l         可以指定value的缺省值:

>>> dict.fromkeys(['name', 'age'], ‘(unknown)’)

{’age’: ‘(unknown)’, ‘name’: ‘(unknown)’}

(4) get:获取项目的value值(不常用)

l         注意下面的区别:

>>> d = {}

>>> print d['name']

Traceback (most recent call last):

  File “<interactive input>”, line 1, in ?

KeyError: ‘name’

>>> print d.get(’name’)

None

l         可以指定缺省值(缺省是None):

>>> d.get(’name’, ‘N/A’)

‘N/A’

(5) has_key:检查Dictionary中是否有指定key

>>> d = {}

>>> d.has_key(’name’)

0

>>> d['name'] = ‘Eric’

>>> d.has_key(’name’)

1

(6) items和iteritems

l         items()以List返回Dictionary中所有项目,每个项目的形式是(key, value):

>>> d = {’title’: ‘Python Web Site’, ‘url’: ‘http://www.python.org‘, ’spam’: 0}

>>> d.items()

[('url', 'http://www.python.org'), ('spam', 0), ('title', 'Python Web Site')]

l         iteritems()返回Iterator对象:

>>> d.iteritems()

<dictionary-itemiterator object at 0×0101CA60>

>>> list(d.iteritems())

[('url', 'http://www.python.org'), ('spam', 0), ('title', 'Python Web Site')]

(7) keys和iterkeys

>>> d.keys()

['url', 'spam', 'title']

>>> d.iterkeys()

<dictionary-keyiterator object at 0×01073720>

>>> list(d.iterkeys())

['url', 'spam', 'title']

(8) pop:根据指定key返回value,并从Dictionary中移去该项目:

>>> d = {’x': 1, ‘y’: 2}

>>> d.pop(’x')

1

>>> d

{’y': 2}

(9) popitem:从Dictionary中随机弹出一个项目返回(Dictionary中的项目是无序的)

>>> d = {’title’: ‘Python Web Site’, ‘url’: ‘http://www.python.org‘, ’spam’: 0}

>>> d.popitem()

(’url’, ‘http://www.python.org‘)

>>> d

{’spam’: 0, ‘title’: ‘Python Web Site’}

(10) setdefault:根据指定的key值,对不在Dictionary的项目设置value值

>>> d = {}

>>> d.setdefault(’name’, ‘N/A’)

‘N/A’

>>> d

{’name’: ‘N/A’}

>>> d['name'] = ‘Gumby’

>>> d.setdefault(’name’, ‘N/A’)

‘Gumby’

>>> d

{’name’: ‘Gumby’}

l         如果不指定缺省值,则使用None

(11) update:使用另一个Dictionary的项目来更新指定Dictionary

>>> d = {’title’: ‘Python Web Site’, ‘url’: ‘http://www.python.org‘, ‘changed’: ‘Mar 14 22:09:15 MET 2005′}

>>> x = {’title’: ‘Python Language Website’}

>>> d.update(x)

>>> d

{’url’: ‘http://www.python.org‘, ‘changed’: ‘Mar 14 22:09:15 MET 2005′, ‘title’: ‘Python Language Website’}

(12) values和itervalues

>>> d.values()

['http://www.python.org', 'Mar 14 22:09:15 MET 2005', 'Python Language Website']

>>> d.itervalues()

<dictionary-valueiterator object at 0×01073900>

>>> list(d.itervalues())

['http://www.python.org', 'Mar 14 22:09:15 MET 2005', 'Python Language Website']

Share and Enjoy:
  • Print this article!
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • RSS
  • Slashdot
  • Technorati
  • TwitThis

Related posts:

  1. 序列、元组、列表、字典
  2. Python用SGMLParser抓取网页连接的改进
  3. Python 3 简介
  4. 在apache上面部署django应用
  5. BlogPump: Blog Post Client with Web Crawler(1) – big picture
  6. Python HTML Parser Performance
  7. Core Python Programming(1) - Basic
  8. 开始Python — List和Tuple(3)
  9. Eclipse SDK + PyDev = Python IDE
  10. Python Programming – Sqlite for data persistence

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Contact us

Admin: Bryan Wu