Python 学习(五):字典和结构化数据

# 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

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值