字典、数据结构化

# 1.像列表一样,字典是许多值的集合,存储方式“键-值”对

# mycat = {'size':'fat','color':'red','disposition':'loud'}
# 这个字典的键:size、color、disposition
# 这个字典的值:fat、red、loud
# 根据“键”获取“值”:print(mycat['size'])

# 2.字典是无序的,且可以用任意值作为键
# spam = {'name':'tom','age':9}
# ha = {'age':9,'name':'tom'}
# print(spam == ha) ---True

#3、keys()/values()/items()方法

# spam = {'color':'red','age':9}
# for i in spam.values():
# print(i) #red 9
#
# for v in spam.keys():
# print(v) #color age
#
# for a,b in spam.items():
# print(a,b) #color red / age 9

# print(list(spam.keys())) #['color', 'age'] 将返回值传给list(转换成列表)

# 4、检查字典中是否存在键或值
# spam = {'color':'red','age':9}
# print('color'in spam.keys() ) #True
# print(9 in spam.values()) #True
# print(9 in spam.keys()) #False
# print(9 not in spam.keys()) #True

# 5、get方法:有两个参数1.要取的值的键,2.若键不存在时,返回备用的值
# spam = {'color':'red','age':9}
# print(spam.get('name','bob')) #bob
# print(spam.get('age','bob')) #9

# 6、setdefault方法:当键没有值的时候,为这个键设置一个默认值。两个参数:1.要检查的键,2.若该键不存在时要给他设置的值,若该键存在,就返回键的值
# spam = {'color':'red','age':9}
# spam.setdefault('name','tom')
# spam.setdefault('color','blue') #因为键“color”存在,因此返回键的值"red"
# print(spam) #{'color': 'red', 'age': 9, 'name': 'tom'}
# 写个小程序:计算一个字符串中每个字符出现的次数
# message = 'It was '
# count = {}
# for i in message: #循环字符串中的每个字符
# count.setdefault(i,0)
# count[i]=count[i]+1
# pprint.pprint(count) #{' ': 2, 'I': 1, 'a': 1, 's': 1, 't': 1, 'w': 1}

# 7、井字棋盘(一个字典,9个键对值)
word = {'top-L':'L','top-M':'M','top-R':'R',
'mid-L':' ','mid-M':' ','mid-R':' ',
'low-L':' ','low-M':' ','low-R':' ',}
def pB(board):
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
print('-+-+-')
print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
print('-+-+-')
print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])
print('-+-+-')
pB(word)
# 打印结果
# L|M|R
# -+-+-
# | |
# -+-+-
# | |
# -+-+-

# 8、物品清单

# all = {'apple':2,'orange':3}
#
# def total(guests):
# num = 0
# for k,v in guests.items():
# print(str(v) + ' '+k)
# num +=v
# print('total number of items:'+str(num))
# total(all)
# 打印结果
# 2 apple
# 3 orange
# total number of items:5
原文地址:https://www.cnblogs.com/ermm/p/7516139.html