学习python(六)

字典

字典的介绍

字典也是python中的一种重要的数据类型,这样就可以定义一个字典了:

>>> apple = {'color':'red','size':'big','texture':'brittle'}
>>> apple
{'color': 'red', 'size': 'big', 'texture': 'brittle'}

将一个字典赋给apple变量,这个字典中的coloer,size,texture表示字典的键,red,texture,brittle表示键所对应的值.字典允许通过键来访问值:

>>> apple['color']
'red'
>>> apple['size']
'big'
>>> apple['texture']
'brittle'

字典和列表除了形式上不一样以外,还有就是字典中存储的数据是无序的,因此这也造成了字典中值是无法通过下标来取到:

#列表是严格按照每个数据的顺序来存储的
>>> lis1 = [1,2,3,4]
>>> lis2 = [2,3,4,1]
>>> lis1 == lis2
False
#字典中内值的顺序是没有要求的
>>> apple1 = {'color':'red','size':'big','texture':'brittle'}
>>> apple2 = {'texture':'brittle','color':'red','size':'big'}
>>> apple1 == apple2
True

向字典内添加一个键值对通常可以这么做:

>>> apple['price'] = 5
>>> apple
{'texture': 'brittle', 'color': 'red', 'size': 'big', 'price': 5}

字典的几个常用重要的函数:

keys()函数

通过keys()函数获取字典中的键(一般我们把获取的数据转换成列表的形式便于操作):

>>> list(apple.keys())
['texture', 'color', 'size', 'price']

values函数

通过values()函数获取字典中的值:

>>> list(apple.values())
['brittle', 'red', 'big', 5]

items()函数

通过items()函数获取字典中的键和值:

>>> list(apple.items())
[('texture', 'brittle'), ('color', 'red'), ('size', 'big'), ('price', 5)]

可以看到每一个键值对都是由一个元组把它们包含了起来.
也可以通过多重赋值的操作更加清晰地显示字典中的键值对:

>>> for k,v in apple.items():
           print('key: ' + k + ' value: ' + str(v))
           
key: texture value: brittle
key: color value: red
key: size value: big
key: price value: 5

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

>>> 'brittle' in apple.values()#检查值
True
>>> 'red' not in apple.values()
False
>>> 'color' in apple.keys()#检查键
True
>>> 'price' in apple.keys()
True
>>> 'weight' in apple.keys()
False

检查键是否存在可以这样简写:

>>> 'color' in apple
True
>>> 'weight' in apple
False

当然检查值是否存在就只能使用values()函数了.

get()函数

get()函数中有两个参数,第一个参数是我们需要检查是否存在的键,第二个参数是如果需要检查的键不存在返回的备用值:

>>> apple.get('color',0)
'red'
>>> apple.get('weight',0)
0

使用get()函数的好处在于,我们可以提前设置一些错误的返回值,这样程序运行的时候就不会因为不重要的一行两行发生错误导致整个程序都停止下来.

setdefault()函数‘

setdefault()函数中有两个参数,第一个参数是我们需要检查是否存在的键值,第二个参数是如果检查的键值不存在需要设置的值:

>>> apple = {'texture': 'brittle', 'color': 'red', 'size': 'big', 'price': 5}
>>> apple.setdefault('color','red')
'red'
>>> apple.setdefault('color','blue')
'red'
>>> apple.setdefault('weight',6)
6
>>> apple
{'texture': 'brittle', 'color': 'red', 'size': 'big', 'price': 5, 'weight': 6}

可以看到,程序的2–5行当键值存在的时候第二个参数并不会起作用,而在程序的第6行当键值不存在的时候,此时setdefault()函数就会将值赋给键,并且将该键值对添加到字典中.这也不乏是一种向字典中添加值的方法.

setdefault()函数的一个应用:统计字符串中各个字符的个数:

str = 'I might have to drop out of school'
count = {}
for i in str:
    count.setdefault(i,0)
    count[i] = count[i] + 1
print(count)

输出:

{'I': 1, ' ': 7, 'm': 1, 'i': 1, 'g': 1, 'h': 3, 't': 3, 'a': 1, 'v': 1, 'e': 1, 'o': 6, 'd': 1, 'r': 1, 'p': 1, 'u': 1, 'f': 1, 's': 1, 'c': 1, 'l': 1}

可以通过导入一个模块儿使结果显示变得更加友好:

import pprint
str = 'I might have to drop out of school'
count = {}
for i in str:
    count.setdefault(i,0)
    count[i] = count[i] + 1
pprint.pprint(count)

结果输出:

{' ': 7,
 'I': 1,
 'a': 1,
 'c': 1,
 'd': 1,
 'e': 1,
 'f': 1,
 'g': 1,
 'h': 3,
 'i': 1,
 'l': 1,
 'm': 1,
 'o': 6,
 'p': 1,
 'r': 1,
 's': 1,
 't': 3,
 'u': 1,
 'v': 1}

两个简单的实例

第一个题目取自《Python编程快速上手—让繁琐工作自动化》page:93:
你在创建一个好玩的视频游戏。用于对玩家物品清单建模的数据结构是一个字典。其中键是字符串,描述清单中的物品,值是一个整型值,说明玩家有多少该物品。例如,字典值{‘rope’: 1, ‘torch’: 6, ‘gold coin’: 42, ‘dagger’: 1, ‘arrow’: 12}意味着玩家有 1 条绳索、6 个火把、42 枚金币等.写一个名为 displayInventory()的函数,它接受任何可能的物品清单,并显示如下:
Inventory:
12 arrow
42 gold coin
1 rope
6 torch
1 dagger
Total number of items: 62
代码如下:

def displayInventory(dict):
    count = 0
    print('Inventory:')
    for key,value in dict.items():
        count = count + value
        print(value,key)
    print('Total number of items:',count)
game = {'rope':1,'torch':6,'gold coin':42,'dagger':1,'arrow':12}
displayInventory(game)

输出结果:

Inventory:
1 rope
6 torch
42 gold coin
1 dagger
12 arrow
Total number of items:  62

第二个题目取自《Python编程快速上手—让繁琐工作自动化》page:94:
假设征服一条龙的战利品表示为这样的字符串列表:dragonLoot = [‘gold coin’, ‘dagger’, ‘gold coin’, ‘gold coin’, ‘ruby’],写一个名为 addToInventory(inventory, addedItems)的函数,其中 inventory 参数是一个字典,表示玩家的物品清单(像前面项目样),addedItems 参数是一个列表,就像 dragonLoot.addToInventory()函数应该返回一个字典,表示更新过的物品清单.
前面的程序(加上前一个项目中的 displayInventory()函数)将输出如下:
Inventory:
45 gold coin
1 rope
1 ruby
1 dagger
Total number of items: 48
代码如下:

def addToInventory(inventory, addedItems):
    for i in addedItems:
        for j , k  in  inventory.items():
            if i == j:
                k = k + 1
                inventory[i] = k
        if i not in inventory.keys():
            inventory.setdefault(i,1)
    return inventory

def displayInventory(dict):
    count = 0
    print('Inventory:')
    for key,value in dict.items():
        count = count + value
        print(value,key)
    print('Total number of items:',count)

inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)

结果输出:

Inventory:
45 gold coin
1 rope
1 dagger
1 ruby
Total number of items: 48
{'gold coin': 45, 'rope': 1, 'dagger': 1, 'ruby': 1}

我在做机器学习的项目的时候,数据预处理中会大量使用列表和字典,其实上述讲的这些字典的操作以及上一篇博客介绍的列表的操作也都只是最最最基本的操作.在做ML项目的时候最常用的就是numpy和pandas两个模块,这两个模块里面有许许多多来操作列表和字典的方式,所以光学这些也只是了解一些基础概念,要想真正达到融会贯通还是需要足够的练习练习练习.
其实列表和字典我还是比较熟悉的,因为之前做项目也就经常用这两个东西.如果我能一直更新博客的话,我一定会写一篇列表字典进阶版的博客.

本文内容主要参考《Python编程快速上手—让繁琐工作自动化》第五章内容,如果有什么错误的地方欢迎指正.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值