《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

附上书上一段精致的示例:
# A simple database 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. labels = { 'phone': 'phone number', 'addr': 'address' } name = raw_input('Name: ') request = raw_input('Phone number (p) or address (a)? ') if request == 'p': key = 'phone' if request == 'a': key = 'addr' if name in people: print "%s's %s is %s." % / (name, labels[key], people[name][key])

---> 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'
修改前面所示的例子:
labels = { 'phone': 'phone number', 'addr': 'address' } name = raw_input('Name: ') request = raw_input('Phone number (p) or address (a)? ') key = request # In case the request is neither 'p' nor 'a' if request == 'p': key = 'phone' if request == 'a': key = 'addr' person = people.get(name, {}) label = labels.get(key, key) result = person.get(key, 'not available') print "%s's %s is %s." % (name, label, result)
--->
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']

你可能感兴趣的:(list,python,url,input,Dictionary,website)