http://blog.csdn.net/ly21st http://ly21st.blog.chinaunix.net
分类: Python/Ruby
2011-09-29 17:10:31
>>> phonebook={'Alice':'2341','Beth':'9102','Cecil':'3258'}
>>> phonebook
{'Beth': '9102', 'Alice': '2341', 'Cecil': '3258'}
注意:字典中的键是唯一的(其他类型的映射也是如此),但值并不唯一。
dict函数:通过其他映射(比如其他字典)或者(键,值)这样的序列对建立字典。
>>> items=[('liyuan',34),('liming',35)]
>>> d=dict(items)
>>> d
{'liming': 35, 'liyuan': 34}
>>> items2=(('liyuan',34),('liming',35))
>>> e=dict(items2)
>>> e
{'liming': 35, 'liyuan': 34}
dict函数也可以通过关键字参数来创建字典:
>>> d=dict(name='Gumby',age=42)
>>> d
{'age': 42, 'name': 'Gumby'}
成员资格: 表达式k in d (d为字典),查找的是键,而不是值。
字典示例:
# 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])
4.2 字典的格式化字符串
>>> phonebook={'Beh':'9102','Alice':'2341','Ceil':'3258'}
>>> phonebook
{'Beh': '9102', 'Alice': '2341', 'Ceil': '3258'}
>>> "Cecil's phone number is %(Ceil)s." % phonebook
"Cecil's phone number is 3258."
4.3 字典的方法
clear方法:
也可以直接在所有字典的类型dict上面调用方法
>>> dict.fromkeys(['name','age'])
{'age': None, 'name': None}
如果不想使用None作为默认值,也可以自己提供默认值。
>>> dict.fromkeys(['name','age'],'(unknow)')
{'age': '(unknow)', 'name': '(unknow)'}
>>> dict.fromkeys(['name','age'],'unknow')
{'age': 'unknow', 'name': 'unknow'}
get方法:一个更宽松的访问字典项的方法。
# A simple database using get()
# Insert database (people) from Listing 4-1 here.
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:
key = request # In case the request is neither 'p' nor 'a'
if request == 'p': key = 'phone'
if request == 'a': key = 'addr'
# Use get to provide default values:
person = people.get(name, {})
label = labels.get(key, key)
result = person.get(key, 'not available')
print "%s's %s is %s." % (name, label, result)
7 keys和iterkeys
keys方法将字典中的键以列表形式返回,而iterkeys则返回针对键的迭代器。
>>> d={'x':1,'y':2}
8 pop方法
>>> d.pop('x')
1
>>> d
{'y': 2}