免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1468 | 回复: 0
打印 上一主题 下一主题

《python 从入门到精通》§4 字典 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-08-16 15:49 |只看该作者 |倒序浏览


  Normal
  0
  
  7.8 磅
  0
  2
  
  false
  false
  false
  
   
   
   
   
   
   
   
   
   
   
   
   
  
  MicrosoftInternetExplorer4



st1\:*{behavior:url(#ieooui) }
/* Style Definitions */
table.MsoNormalTable
        {mso-style-name:普通表格;
        mso-tstyle-rowband-size:0;
        mso-tstyle-colband-size:0;
        mso-style-noshow:yes;
        mso-style-parent:"";
        mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
        mso-para-margin:0cm;
        mso-para-margin-bottom:.0001pt;
        mso-pagination:widow-orphan;
        font-size:10.0pt;
        font-family:"Times New Roman";
        mso-fareast-font-family:"Times New Roman";
        mso-ansi-language:#0400;
        mso-fareast-language:#0400;
        mso-bidi-language:#0400;}

  Normal
  0
  
  7.8 磅
  0
  2
  
  false
  false
  false
  
   
   
   
   
   
   
   
   
   
   
   
   
  
  MicrosoftInternetExplorer4



/* Style Definitions */
table.MsoNormalTable
        {mso-style-name:普通表格;
        mso-tstyle-rowband-size:0;
        mso-tstyle-colband-size:0;
        mso-style-noshow:yes;
        mso-style-parent:"";
        mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
        mso-para-margin:0cm;
        mso-para-margin-bottom:.0001pt;
        mso-pagination:widow-orphan;
        font-size:10.0pt;
        font-family:"Times New Roman";
        mso-fareast-font-family:"Times New Roman";
        mso-ansi-language:#0400;
        mso-fareast-language:#0400;
        mso-bidi-language:#0400;}
§4 字典
2009-8-16
磁针石:xurongzhong#gmail.com
博客:
oychw.cublog.cn
phonebook = {'Alice': '2341', 'Beth': '9102', 'Cecil':
'3258'}
key具有唯一性

函数:
>>> items = [('name', 'Gumby'),
('age', 42)]
>>> d = dict(items)
>>> d
{'age': 42, 'name': 'Gumby'}
>>> d['name']
'Gumby'

>>> d = dict(name='Gumby', age=42)
>>> d
{'age': 42, 'name': 'Gumby'}

基本操作:
       ?
len(d) returns the number of items (key-value pairs) in d.
? d[k] returns the value associated with
the key k.
? d[k] = v associates the value v with the
key k.
? del
d[k] deletes the item with key k.
? k in d checks whether there is an item in
d that has the key k.

       key可以为不变的类型。
       自动添加
      
       >>>
x = {}
>>> x[42] = 'Foobar'
>>> x
{42: 'Foobar'}

实例:

# A simple database

# A dictionary with person names as keys.
Each person is represented as
# another dictionary with the keys 'phone'
and 'addr' referring to their phone
# number and address, respectively.

people = {

    'Alice': {
      
'phone': '2341',
      
'addr': 'Foo drive 23'
   
},

   
'Beth': {
      
'phone': '9102',
      
'addr': 'Bar street
42'
   
},

   
'Cecil': {
      
'phone': '3158',
      
'addr': 'Baz avenue
90'
    }

}

# Descriptive labels for the phone number
and address. These will be used
# when printing the output.
labels = {
   
'phone': 'phone number',
    'addr': 'address'
}

name = raw_input('Name: ')

# Are we looking for a phone number or an
address?
request = raw_input('Phone number (p) or
address (a)? ')

# Use the correct key:
if request == 'p': key = 'phone'
if request == 'a': key = 'addr'

# Only try to print information if the name
is a valid key in
# our dictionary:
if name in people: print "%s's %s is
%s." % \
   
(name, labels[key], people[name][key])
   
    运行结果:
   
Name: Beth
Phone number (p) or address (a)? p
Beth's phone number is 9102.

格式化输出:
>>> phonebook
{'Beth': '9102', 'Alice': '2341', 'Cecil': '3258'}
>>> "Cecil's phone number is
%(Cecil)s." % phonebook
"Cecil's phone number is 3258."

字典方法:
清除:clear

>>> x = {}
>>> y = x
>>> x['key'] = 'value'
>>> y
{'key': 'value'}
>>> x = {}
>>> y
{'key': 'value'}
And here’s the second scenario:
>>> x = {}
>>> y = x
>>> x['key'] = 'value'
>>> y
{'key': 'value'}
>>> x.clear()
>>> y
{}

复制:copy

>>> 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']}

>>> 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']}

复制key:fromkeys
>>> {}.fromkeys(['name', 'age'])
{'age': None, 'name': None}

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

获取:
>>> d = {}
>>> print d['name']
Traceback (most recent call last):
File "", line 1, in
?
KeyError: 'name'
>>> print d.get('name')
None

>>> d.get('name', 'N/A')
'N/A'

是否有key:
列出值:items and
iteritems
列出关键字:keys and
iterkeys
取值:pop
>>> d = {'x': 1, 'y': 2}
>>> d.pop('x')
1
>>> d
{'y': 2}
出栈:popitem
       但是没有append。
setdefault:设置默认值。

更新:update
>>> d = {
'title': 'Python Web Site',
'url': 'http://www.python.org',
'changed': 'Mar 14 22:09:15 MET 2008'
}
>>> x = {'title': 'Python Language
Website'}
>>> d.update(x)
>>> d
{'url': 'http://www.python.org', 'changed':
'Mar 14 22:09:15 MET 2008', 'title':
'Python Language Website'}


取值:values and
itervalues

               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/21908/showart_2029242.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP