# Python 5.字典和结构化数据
# 字典是许多值的集合。但不像列表的下标,字典的索引可以使用许多不同数据类型,不只是整数
# 字典的索引被称为“键”,键及其关联的值称为“键-值”对。
# 例如
myData = {'size': '30', 'color': 'white', 'pos': 'left'}
# 键:size, color, pos
# 键值:30, white, left
print(myData['size'])
# 字典可以用整数值作为键,但不必从0开始可以是任意数字
# 字典中的表项是不排序的,判断两个字典相等,需要所有的键和键值相等,顺序不重要。
# 访问字典中没有的键,是会报错的
#print(myData['d'])
#结果:KeyError: 'd'
# 重新赋值
myData['size'] = 10
print(myData['size'])
# keys(), values() 和 items() 方法
# keys() 返回字典的键
# values() 返回字典的值
# items() 返回字典的键-值
for x in myData.keys():
print(x)
for x in myData.values():
print(x)
for x in myData.items():
print(x)
# 检查字典中是否存在键和值 用in来判断
if 10 in myData.values():
print(True)
else:
print(False)
# get()方法 它有两个参数
# 一个是取得其值的键
# 另一个是如果该键不存在时,返回第二个参数值
print(myData.get('size1', 30))
# setdefault()方法 两个参数
# 第一个参数是键
# 第二个是键值
# 使用方法:如果该键值不存在,则增加键-值,返回键值;如果存在则返回该原键值。
myData = {'size': '30', 'color': 'white', 'pos': 'left'}
myData.setdefault('name', 'kyle')
print(myData)
x = myData.setdefault('size', '10')
print(x)
# 例子: 统计字符的个数
import pprint
mes = 'I am kyle'
count = {}
for x in mes:
count.setdefault(x, 0)
count[x] = count[x] + 1
pprint.pprint(count)
# 嵌套的字典和列表
fruits = {'kyle' :{'apples': 5, 'eggs':8},
'ace':{'eggs':1, 'orange':2},
'jone':{'bana':12, 'apples': 2}
}
cnts = 0
def totalAll(allFruit, item):
cnts = 0
for k, v in allFruit.items():
cnts = cnts + v.get(item,0)
return cnts
print('apple :' + str(totalAll(fruits, 'apples')))
print('eggs :' + str(totalAll(fruits, 'eggs')))
print('orange :' + str(totalAll(fruits, 'orange')))
print('bana :' + str(totalAll(fruits, 'bana')))
print('cake :' + str(totalAll(fruits, 'cake')))
#结果
apple :7
eggs :9
orange :2
bana :12
cake :0