《Beginning Python From Novice to Professional》学习笔记六:Dictionary

1.创建(注意Dictionary是没有顺序的)
phonebook = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
冒号之前为key,之后为value,key必须具有唯一性。
items = [('name', 'Gumby'), ('age', 42)]
d = dict(items)
---> {'age': 42, 'name': 'Gumby'}
d = dict(name='Gumby', age=42)
---> {'age': 42, 'name': 'Gumby'}

2.Basic操作
len(dic)、d[key]、d[key] = val、del d[key]、key in dic
其中关于赋值要注意
x = {}
x[42] = 'Foobar'
---> {42: 'Foobar'}   #但在List中这样的操作是非法的,除非将x初始化为[None]*43

附上书上一段精致的示例:


---> Here is a sample run of the program:
Name: Beth
Phone number (p) or address (a)? p
Beth's phone number is 9102.


3.用Dictionary来格式化String
phonebook = {'Beth': '9102', 'Alice': '2341', 'Cecil': '3258'}
"Cecil's phone number is %(Cecil)s." % phonebook
---> "Cecil's phone number is 3258."

一个实用的Dictionary在模板生成中的应用示例:
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>

#类似效果也可以用string.Template来实现

4.clear清空,无返回
returned_value = d.clear()
d
---> {}
print returned_value
---> None

5.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']}
#when you replace a value in the copy, the original is unaffected. if you modify a value, the original is changed as well because the same value is stored there. 归根到底是因为如果Value中用的是List,由于Python的引用性,实际存储的是List对象的地址,因此对Value的改变依然会影响前者。—— thy
改用copy库中的deepcopy函数可以改变,它将所有的引用处均作值拷贝
import copy
d = {}
d['names'] = ['Alfred', 'Bertrand']
c = d.copy()
dc = copy.deepcopy(d)
d['names'].append('Clive')
c
---> {'names': ['Alfred', 'Bertrand', 'Clive']}
dc
---> {'names': ['Alfred', 'Bertrand']}

6.fromkeys用给定的Keys创建新的Dictionary
{}.fromkeys(['name', 'age'])
---> {'age': None, 'name': None}
dict.fromkeys(['name', 'age'], 'thy')
---> {'age': 'thy', 'name': 'thy'}

7.get取值,但无如则返回一个特定的值而不会产生Exception
d = {}
print d.get('name')
---> None
d.get('name', 'N/A')   #用'N/A'代替默认的None
---> 'N/A'
d['name'] = 'Eric'
d.get('name')
---> 'Eric'
修改前面所示的例子:

--->
Name: Gumby
Phone number (p) or address (a)? batting average
Gumby's batting average is not available.


8.has_key指定的Key是否存在
d = {}
d.has_key('name')
---> False
d['name'] = 'Eric'
d.has_key('name')
---> True

9.items and iteritems
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')]
#items返回一个由(key,value)的Tuple形式组成的无序List。
而iteritems会返回一个迭代器(Iterator)。

10.keys and iterkeys
d.keys()
---> ['url', 'spam', 'title']
#iterkeys同9所述

11.pop对key模仿栈操作
d = {'x': 1, 'y': 2}
d.pop('x')
---> 1
d
---> {'y': 2}

12.popitem对任一对(key,value)模仿栈操作
d = {'url': 'http://www.python.org', 'spam': 0, 'title': 'Python Web Site'}
d.popitem()
---> ('url', 'http://www.python.org')
d
---> {'spam': 0, 'title': 'Python Web Site'}

13.setdefault类似于get方法
d = {}
d.setdefault('name', 'N/A')
---> 'N/A'
#这样在'name'未赋真正的值时默认为'N/A',一旦赋值后'N/A'便不存在了
d = {}
print d.setdefault('name')
---> None
#PS,setdefault会返回对默认值的引用,接上例看下面代码:
t=d.setdefault('sex', [])   #此时t成为其后[]的引用
t.append('F')
d   ---> {'name', 'N/A', 'sex': ['F']}

14.update更新已有key的value
d = {'url': 'http://www.python.org', 'spam': 0, 'title': 'Python Web Site'}
x = {'title': 'Python Language Website'}
d.update(x)
d
---> {'url': 'http://www.python.org', 'spam': 0, 'title': 'Python Language Website'}

15.values and itervalues
values返回由value组成的List(与keys不同的是,这样生成的List中可能会有相同值)
d.values()
---> ['http://www.python.org', 0, 'Python Language Website']
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Gain a fundamental understanding of Python’s syntax and features with the second edition of Beginning Python, an up–to–date introduction and practical reference. Covering a wide array of Python–related programming topics, including addressing language internals, database integration, network programming, and web services, you’ll be guided by sound development principles. Ten accompanying projects will ensure you can get your hands dirty in no time. Updated to reflect the latest in Python programming paradigms and several of the most crucial features found in the forthcoming Python 3.0 (otherwise known as Python 3000), advanced topics, such as extending Python and packaging/distributing Python applications, are also covered. What you’ll learn * Become a proficient Python programmer by following along with a friendly, practical guide to the language’s key features. * Write code faster by learning how to take advantage of advanced features such as magic methods, exceptions, and abstraction. * Gain insight into modern Python programming paradigms including testing, documentation, packaging, and distribution. * Learn by following along with ten interesting projects, including a P2P file–sharing application, chat client, video game, remote text editor, and more. Complete, downloadable code is provided for each project! Who is this book for? Programmers, novice and otherwise, seeking a comprehensive introduction to the Python programming language. About the Apress Beginning Series The Beginning series from Apress is the right choice to get the information you need to land that crucial entry–level job. These books will teach you a standard and important technology from the ground up because they are explicitly designed to take you from “novice to professional.” You’ll start your journey by seeing what you need to know—but without needless theory and filler. You’ll build your skill set by learning how to put together real–world projects step by step. So whether your goal is your next career challenge or a new learning opportunity, the Beginning series from Apress will take you there—it is your trusted guide through unfamiliar territory!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值