@zhangyu756897669
2017-08-28T15:48:12.000000Z
字数 4974
阅读 590
python官方文档
在本章中,我将介绍字典数据类型,它提供了访问和组织数据的灵活方式。然后,结合词典与上一章的列表知识,您将学习如何创建一个数据结构来建模一个tic-tac-toe板。
像列表一样,字典是许多值的集合。但是与列表的索引不同,词典的索引可以使用许多不同的数据类型,而不仅仅是整数。词典的索引称为密钥,具有关联值的键称为键值对。
在代码中,一个字典用大括号{}
myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}
这将为myCat变量分配一个字典。这个字典的键是“大小”,“颜色”和“处置”。这些键的值分别为“胖”,“灰”和“大”。您可以通过键来访问这些值:
myCat['size']
'fat'
'My cat has ' + myCat['color'] + ' fur.'
'My cat has gray fur.'
字典仍然可以使用整数值作为键,就像列表使用整数索引一样,但是它们不必从0开始,可以是任何数字。
spam = {12345: 'Luggage Combination', 42: 'The Answer'}
与列表不同,词典中的项目无序。名为spam的列表中的第一个项目是spam[0]。但字典中没有“第一”项。虽然项目的顺序对于确定两个列表是否相同是重要的,但键字对中键入字典的顺序并不重要。
spam = ['cats', 'dogs', 'moose']
bacon = ['dogs', 'moose', 'cats']
spam == bacon
False
eggs = {'name': 'Zophie', 'species': 'cat', 'age': '8'}
ham = {'species': 'cat', 'age': '8', 'name': 'Zophie'}
eggs == ham
True
因为字典没有被排序,它们不能像列表那样切片。
尝试访问字典中不存在的键将导致一个KeyError错误消息,非常像列表的“超范围”IndexError错误消息。在交互式shell中输入以下内容,并注意由于没有“color”键而显示的错误消息:
spam = {'name': 'Zophie', 'age': 7}
spam['color']
Traceback (most recent call last):
File "", line 1, in
spam['color']
KeyError: 'color'
虽然字典不像列表一样,但是字典的密钥可以为任意值能够使你以强大的方式组织数据。假设您希望程序存储有关您朋友的生日的数据。您可以使用名称作为键和生日作为值的字典。
birthdays = {'Alice': 'Apr 1', 'Zhang': 'Dec 12', 'Yu': 'Mar 4'}
while True:
print('Enter a name: (blank to quit)')
name = input()
if name == '':
break
if name in birthdays:
print(birthdays[name] + ' is the birthday of ' + name)
else:
print('I do not have birthday information for ' + name)
print('What is their birthday?')
bday = input()
birthdays[name] = bday
print('Birthday database updated.')
当你运行这个程序,它将如下所示:
>
Enter a name: (blank to quit)
Alice
Apr 1 is the birthday of Alice
Enter a name: (blank to quit)
Zhang
Dec 12 is the birthday of Zhang
Enter a name: (blank to quit)
Yu
Mar 4 is the birthday of Yu
Enter a name: (blank to quit)
hah
I do not have birthday information for hah
What is their birthday?
当然,当程序终止时,您在此程序中输入的所有数据都被遗忘。第8章将学习如何将数据保存到硬盘驱动器上的文件。
有三种字典方法将返回词典的键,值或键和值两者的类似列的值:keys(),values()和items()。这些方法返回的值不是真正的列表:它们不能被修改,没有append()方法。但是这些数据类型(dict_keys,dict_values和dict_items分别)可以在for循环中使用。
spam = {'color': 'red', 'age': 42}
for v in spam.values():
print(v)
red
42
这里,for循环遍历spam词典中的每个值。一个for循环也可以遍历键或者两个键和值:
for k in spam.keys():
print(k)
color
age
for i in spam.items():
print(i)
('color', 'red')
('age', 42)
spam = {'color': 'red', 'age': 42}
spam.keys()
dict_keys(['color', 'age'])
list(spam.keys())
['color', 'age']
['color', 'age']
列表(spam.keys())将从keys()返回的dict_keys值传递给list(),然后返回列表值['color','age']。
spam = {'color': 'red', 'age': 42}
for k, v in spam.items():
print('Key: ' + k + ' Value: ' + str(v))
Key: color Value: red
Key: age Value: 42
运算符中的in和not能检查列表中是否存在值。您还可以使用这些运算符来查看字典中是否存在某个键或值。
spam = {'name': 'Zophie', 'age': 7}
'name' in spam.keys()
True
'Zophie' in spam.values()
True
'color' in spam.keys()
False
'color' not in spam.keys()
True
在访问该密钥的值之前,检查字典中是否存在密钥是枯燥的。幸运的是,字典有一个get()方法,它有两个参数:要检索的值的键值,如果该键不存在则返回一个返回值。
picnicItems = {'apples': 5, 'cups': 2}
'I am bringing ' + str(picnicItems.get('cups', 0)) + ' cups.'
'I am bringing 2 cups.'
'I am bringing ' + str(picnicItems.get('eggs', 0)) + ' eggs.'
'I am bringing 0 cups.'
因为picnicItems字典中没有“egg”键,所以get()方法返回默认值0。没有使用get(),代码会导致一个错误消息,例如在下面的例子中:
picnicItems = {'apples': 5, 'cups': 2}
'I am bringing ' + str(picnicItems['eggs']) + ' eggs.'
KeyError Traceback (most recent call last)
in ()
1 picnicItems = {'apples': 5, 'cups': 2}
----> 2 'I am bringing ' + str(picnicItems['eggs']) + ' eggs.'KeyError: 'eggs'
您通常必须为字典中的某个键设置一个值,当该键在字典中还没有值,确定一个返回值时,代码看起来像这样:
spam = {'name': 'Pooka', 'age': 5}
if 'color' not in spam:
spam['color'] = 'black'
setdefault() 方法提供了一行代码中的方法。传递给该方法的第一个参数是检查的关键字,第二个参数是该键不存在时设置的值。如果密钥确实存在,setdefault()方法返回密钥的值。
spam = {'name': 'Pooka', 'age': 5}
spam.setdefault('color', 'black')
'black'
spam
{'age': 5, 'color': 'black', 'name': 'Pooka'}
setdefault() 方法是确保键存在的一个很好的快捷方式。这是一个简短的程序,用于计算字符串中每个字母的出现次数
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
print(count)
{'I': 1, 't': 6, ' ': 13, 'w': 2, 'a': 4, 's': 3, 'b': 1, 'r': 5, 'i': 6, 'g': 2, 'h': 3, 'c': 3, 'o': 2, 'l': 3, 'd': 3, 'y': 1, 'n': 4, 'A': 1, 'p': 1, ',': 1, 'e': 5, 'k': 2, '.': 1}
该程序循环消息变量的字符串中的每个字符,计算每个字符出现的频率。 setdefault()方法调用确保键位于计数字典(默认值为0),因此当执行count [character] = count [character] 1时,程序不会引发KeyError错误。
从输出中可以看到小写字母c出现3次,空格字符出现13次,大写字母A出现1次。这个程序将工作,无论什么字符串在消息变量内,即使字符串是数百万个字符长!
如果您将pprint模块导入到程序中,您将可以访问将“漂亮打印”字典值的pprint()和pformat()函数。当您希望更清晰地显示字典中的项目而不是print()提供的内容时,这是有帮助的。
import pprint
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)
{' ': 13,
',': 1,
'.': 1,
'A': 1,
'I': 1,
'a': 4,
'b': 1,
'c': 3,
'd': 3,
'e': 5,
'g': 2,
'h': 3,
'i': 6,
'k': 2,
'l': 3,
'n': 4,
'o': 2,
'p': 1,
'r': 5,
's': 3,
't': 6,
'w': 2,
'y': 1}
当字典本身包含嵌套列表或字典时,pprint.pprint()函数特别有用。
如果要将精美文本作为字符串值获取,而不是在屏幕上显示,请调用pprint.pformat()。这两行相同:
pprint.pprint(count)
print(pprint.pformat(count))