[关闭]
@zhangyu756897669 2017-08-28T15:48:12.000000Z 字数 4974 阅读 590

Python官方文档

python官方文档


字典和数据结构

在本章中,我将介绍字典数据类型,它提供了访问和组织数据的灵活方式。然后,结合词典与上一章的列表知识,您将学习如何创建一个数据结构来建模一个tic-tac-toe板。

字典数据类型

像列表一样,字典是许多值的集合。但是与列表的索引不同,词典的索引可以使用许多不同的数据类型,而不仅仅是整数。词典的索引称为密钥,具有关联值的键称为键值对。
在代码中,一个字典用大括号{}

  1. myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}

这将为myCat变量分配一个字典。这个字典的键是“大小”,“颜色”和“处置”。这些键的值分别为“胖”,“灰”和“大”。您可以通过键来访问这些值:

  1. myCat['size']

'fat'

  1. 'My cat has ' + myCat['color'] + ' fur.'

'My cat has gray fur.'

字典仍然可以使用整数值作为键,就像列表使用整数索引一样,但是它们不必从0开始,可以是任何数字。

  1. spam = {12345: 'Luggage Combination', 42: 'The Answer'}

字典 VS 列表

与列表不同,词典中的项目无序。名为spam的列表中的第一个项目是spam[0]。但字典中没有“第一”项。虽然项目的顺序对于确定两个列表是否相同是重要的,但键字对中键入字典的顺序并不重要。

  1. spam = ['cats', 'dogs', 'moose']
  2. bacon = ['dogs', 'moose', 'cats']
  3. spam == bacon

False

  1. eggs = {'name': 'Zophie', 'species': 'cat', 'age': '8'}
  2. ham = {'species': 'cat', 'age': '8', 'name': 'Zophie'}
  3. eggs == ham

True

因为字典没有被排序,它们不能像列表那样切片。

尝试访问字典中不存在的键将导致一个KeyError错误消息,非常像列表的“超范围”IndexError错误消息。在交互式shell中输入以下内容,并注意由于没有“color”键而显示的错误消息:

  1. spam = {'name': 'Zophie', 'age': 7}
  2. spam['color']

Traceback (most recent call last):
File "", line 1, in
spam['color']
KeyError: 'color'

虽然字典不像列表一样,但是字典的密钥可以为任意值能够使你以强大的方式组织数据。假设您希望程序存储有关您朋友的生日的数据。您可以使用名称作为键和生日作为值的字典。

  1. birthdays = {'Alice': 'Apr 1', 'Zhang': 'Dec 12', 'Yu': 'Mar 4'}
  2. while True:
  3. print('Enter a name: (blank to quit)')
  4. name = input()
  5. if name == '':
  6. break
  7. if name in birthdays:
  8. print(birthdays[name] + ' is the birthday of ' + name)
  9. else:
  10. print('I do not have birthday information for ' + name)
  11. print('What is their birthday?')
  12. bday = input()
  13. birthdays[name] = bday
  14. 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章将学习如何将数据保存到硬盘驱动器上的文件。

The keys(), values(), and items() Methods

有三种字典方法将返回词典的键,值或键和值两者的类似列的值:keys(),values()和items()。这些方法返回的值不是真正的列表:它们不能被修改,没有append()方法。但是这些数据类型(dict_keys,dict_values和dict_items分别)可以在for循环中使用。

  1. spam = {'color': 'red', 'age': 42}
  2. for v in spam.values():
  3. print(v)

red
42

这里,for循环遍历spam词典中的每个值。一个for循环也可以遍历键或者两个键和值:

  1. for k in spam.keys():
  2. print(k)

color
age

  1. for i in spam.items():
  2. print(i)

('color', 'red')
('age', 42)

  1. spam = {'color': 'red', 'age': 42}
  2. spam.keys()

dict_keys(['color', 'age'])

  1. list(spam.keys())
  2. ['color', 'age']

['color', 'age']

列表(spam.keys())将从keys()返回的dict_keys值传递给list(),然后返回列表值['color','age']。

  1. spam = {'color': 'red', 'age': 42}
  2. for k, v in spam.items():
  3. print('Key: ' + k + ' Value: ' + str(v))

Key: color Value: red
Key: age Value: 42

检查字典中是否存在键或值

运算符中的in和not能检查列表中是否存在值。您还可以使用这些运算符来查看字典中是否存在某个键或值。

  1. spam = {'name': 'Zophie', 'age': 7}
  2. 'name' in spam.keys()

True

  1. 'Zophie' in spam.values()

True

  1. 'color' in spam.keys()

False

  1. 'color' not in spam.keys()

True

get()方法

在访问该密钥的值之前,检查字典中是否存在密钥是枯燥的。幸运的是,字典有一个get()方法,它有两个参数:要检索的值的键值,如果该键不存在则返回一个返回值。

  1. picnicItems = {'apples': 5, 'cups': 2}
  2. 'I am bringing ' + str(picnicItems.get('cups', 0)) + ' cups.'

'I am bringing 2 cups.'

  1. 'I am bringing ' + str(picnicItems.get('eggs', 0)) + ' eggs.'

'I am bringing 0 cups.'

因为picnicItems字典中没有“egg”键,所以get()方法返回默认值0。没有使用get(),代码会导致一个错误消息,例如在下面的例子中:

  1. picnicItems = {'apples': 5, 'cups': 2}
  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'

setdefault()方法

您通常必须为字典中的某个键设置一个值,当该键在字典中还没有值,确定一个返回值时,代码看起来像这样:

  1. spam = {'name': 'Pooka', 'age': 5}
  2. if 'color' not in spam:
  3. spam['color'] = 'black'

setdefault() 方法提供了一行代码中的方法。传递给该方法的第一个参数是检查的关键字,第二个参数是该键不存在时设置的值。如果密钥确实存在,setdefault()方法返回密钥的值。

  1. spam = {'name': 'Pooka', 'age': 5}
  2. spam.setdefault('color', 'black')

'black'

  1. spam

{'age': 5, 'color': 'black', 'name': 'Pooka'}

setdefault() 方法是确保键存在的一个很好的快捷方式。这是一个简短的程序,用于计算字符串中每个字母的出现次数

  1. message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
  2. count = {}
  3. for character in message:
  4. count.setdefault(character, 0)
  5. count[character] = count[character] + 1
  6. 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}

漂亮的印刷

如果您将pprint模块导入到程序中,您将可以访问将“漂亮打印”字典值的pprint()和pformat()函数。当您希望更清晰地显示字典中的项目而不是print()提供的内容时,这是有帮助的。

  1. import pprint
  2. message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
  3. count = {}
  4. for character in message:
  5. count.setdefault(character, 0)
  6. count[character] = count[character] + 1
  7. 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()。这两行相同:

  1. pprint.pprint(count)
  1. print(pprint.pformat(count))
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注