Python字典和结构化数据

字典数据类型

1
2
3
4
5
6
7
8
9
10
>>> mycat = {'size':'fat','color':'gray','disposition':'loud'}
>>> mycat
{'size': 'fat', 'color': 'gray', 'disposition': 'loud'}
>>> mycat['size']
'fat'
>>> spam = {123:'hello',456:'word'}
>>> spam
{123: 'hello', 456: 'word'}
>>> spam[123]
'hello'

字典与列表

字典的相等不考虑元素的位置,而列表必须位置一致

1
2
3
4
5
6
7
8
>>> spam1 = {123:'hello',456:'word'}
>>> spam2 = {456:'word',123:'hello'}
>>> spam1 == spam2
True
>>> spam1 = [1,2,3]
>>> spam2 = [3,2,1]
>>> spam1 == spam2
False

字典的动态查询与添加

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
birthdays = {}
while True:
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 of ' + name)
print('What is their birthday')
birthday = input()
birthdays[name] = birthday
print('Birthday database updated.')
for i in birthdays:
print(i +' 的生日在 '+birthdays[i])
print(birthdays)

keys()、values()和items()方法

1
2
3
4
5
6
7
>>> spam = {'color': 'red', 'age': '10'}
>>> for i in spam:
... print('key = ' + i + ', value = ' + spam[i])
...
key = color, value = red
key = age, value = 10
>>>

直接写 for i in spam 固然简单,但当遇到value的字符类型不一样的时候,就会报错

1
2
3
4
5
6
7
8
9
>>> spam = {'color': 'red', 'age': 10}
>>> for i in spam:
... print('key = ' + i + ', value = ' + spam[i])
...
key = color, value = red
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>>

使用 spam.keys() 可以遍历字典中的key

1
2
3
4
5
>>> for i in spam.keys():
... print(i)
...
color
age

使用 spam.values() 可以遍历字典中的value

1
2
3
4
5
>>> for i in spam.values():
... print(i)
...
red
10

使用 spam.items() 可以遍历字典中的(key, value)

1
2
3
4
5
>>> for i in spam.items():
... print(i)
...
('color', 'red')
('age', 10)

与列表转换

1
2
3
4
5
6
7
8
9
10
11
>>> spam
{'color': 'red', 'age': 10}
>>> spam.keys()
['color', 'age']
>>> list(spam.keys())
['color', 'age']
>>> spam.items()
[('color', 'red'), ('age', 10)]
>>> spam.values()
['red', 10]
>>>

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

1
2
3
4
5
6
7
8
>>> spam
{'color': 'red', 'age': 10}
>>> 'name' in spam.keys()
False
>>> 'color' in spam.keys()
True
>>> 'red' in spam.values()
True

get()方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#使用get()
>>> temp = {'apple': 5, 'banana': 6}
>>> 'I am bringing ' + str(temp.get('apple',0)) + ' apple'
'I am bringing 5 apple'
>>> 'I am bringing ' + str(temp.get('eggs',0)) + ' eggs'
'I am bringing 0 eggs'
>>> temp
{'apple': 5, 'banana': 6}

#未使用get()
>>> 'I am bringing ' + str(temp['apple']) + ' apples'
'I am bringing 5 apples'
>>> 'I am bringing ' + str(temp['eggs']) + ' eggs'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'eggs'

setdefault()方法

在字典中为某个键值设置一个默认值,当该键没有任何值使用时,默认值生效

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> spam
{'color': 'red', 'age': 10}
>>> spam.setdefault('name', 'Tom')
'Tom'
>>> spam
{'color': 'red', 'age': 10, 'name': 'Tom'}
>>> spam.setdefault('name', 'Joy')
'Tom'
>>> spam
{'color': 'red', 'age': 10, 'name': 'Tom'}
>>> spam['name'] = 'Lili'
>>> spam
{'color': 'red', 'age': 10, 'name': 'Lili'}

漂亮打印

1
2
3
4
5
6
7
8
import pprint

temp = 'Yes, I can do it.'
count = {}
for i in temp:
count.setdefault(i, 0)
count[i] = count[i] + 1
pprint.pprint(count)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{' ': 4,
',': 1,
'.': 1,
'I': 1,
'Y': 1,
'a': 1,
'c': 1,
'd': 1,
'e': 1,
'i': 1,
'n': 1,
'o': 1,
's': 1,
't': 1}

使用数据结构对真实世界建模

  • 井字棋盘
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# -*- coding: utf-8 -*-

tboard = {'T-L': ' ', 'T-C': ' ', 'T-R': ' ',
'M-L': ' ', 'M-C': ' ', 'M-R': ' ',
'B-L': ' ', 'B-C': ' ', 'B-R': ' '}

'''
tboard = {}
for a in ['T','M','B']:
for b in ['L','C','R']:
tboard.setdefault(a + '-' + b, ' ')
'''

def func(board):
print(board['T-L'] + '|' + board['T-C'] + '|' + board['T-R'])
print(board['M-L'] + '|' + board['M-C'] + '|' + board['M-R'])
print(board['B-L'] + '|' + board['B-C'] + '|' + board['B-R'])

turn = 'X'
for i in range(9):
func(tboard)
print(u'请 ' + turn + u' 选定位置')
temp = input() # 输入"T-L" 等
tboard[temp] = turn
if turn == 'X':
turn = 'O'
else:
turn = 'X'

嵌套字典和列表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
all = {'Tom':{'Apple':4, 'Egg':3},
'Lili':{'Banana':2, 'Apple':2},
'Joy':{'Orange':3, 'Egg':2}
}
def totalBrought(temp, item):#指定查询
num = 0
for v in temp.values():
num = num + v.get(item, 0)
return num

def func(temp): #全部查询
for v in temp.values():
for a in v.keys():
t.setdefault(a, 0)
t[a] = t[a] + v[a]
t = {}
func(all)
for k,v in t.items():
print('统一查询:' + k + ' = ' + str(v))
print()
print('指定查询:Apple = ' + str(totalBrought(all, 'Apple')))

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :