Python基础_字典

第5章_字典和结构化数据
1、keys()、values()、items()方法
  • 返回的数据类型分别是dict_keys()、dict_values()、dict_items()
spam = {'color': 'red', 'ages': 42}
for k in spam.keys():
    print(k, end=' ')
print()
>>>>> color ages 
for v in spam.values():
    print(v, end=' ')
print()
>>>>> red 42 
for k, v in spam.items():
    print(k, v, end=' ')
>>>>> color red ages 42
2、检查字典中是否存在键或值
spam = {'color': 'red', 'ages': 42}
#'color' in spam 等价于'color' in spam.keys()
'color' in spam
>>>>> True
'red' in spam.values()
>>>>> True
3、字典的get()方法返回值
  • 字典有一个get()方法,它有两个参数:要取得其值的键,以及如果该键不存在时,返回的备用值。不会改变字典
spam = {'color': 'red', 'ages': 42}
spam.get('color')
>>>>>  'red'
spam.get('color', 'green')
>>>>>  'red'
spam.get('name', 'mike')
>>>>>  'mike'
print(spam)
>>>>> {'color': 'red', 'ages': 42}
4、setdefault()方法
  • 字典传递给该方法的第一个参数,是要检查的键。第二个参数,是如果该键不存在时要设置的值,如果该键确实存在,方法就会返回键的值。可能改变字典
spam = {'color': 'red', 'ages': 42}
spam.setdefault('name', 'pooka')
>>>>> 'pooka'
print(spam)
>>>>> {'color': 'red', 'ages': 42, 'name': 'pooka'}
spam.setdefault('color','black')
>>>>>  'red'
print(spam)
>>>>>  {'color': 'red', 'ages': 42, 'name': 'pooka'}
5、漂亮打印
import pprint
message = 'it was a bright cold day in April'
count = {}
for ch in message:
    count.setdefault(ch, 0)
    count[ch] = count[ch] + 1
pprint.pprint(count)
>>>>> 输出:
{' ': 7,
 'A': 1,
 'a': 3,
 'b': 1,
 'c': 1,
 'd': 2,
 'g': 1,
 'h': 1,
 'i': 4,
 'l': 2,
 'n': 1,
 'o': 1,
 'p': 1,
 'r': 2,
 's': 1,
 't': 2,
 'w': 1,
 'y': 1}
6、创建字典的多种方法
  • 创建空字典
dic ={}
  • 直接赋值创建
dic = {'apple':'red','pen':1,'sex':'male'}
  • 字典键值表,通过关键字创建字典;注意键没有引号
dic = dict(apple='red',pen=1,color=['red','green','blue'])
>>>>> {'apple': 'red', 'pen': 1, 'color': ['red', 'green', 'blue']}
  • 字典键值元组表:通过二元组列表创建;注意:键是要用引号
list = [('apple','red'),('pen',1),('color',['red','green','blue'])]
dic = dict(list)
>>>>> {'apple': 'red', 'pen': 1, 'color': ['red', 'green', 'blue']}
  • dict和zip结合创建;zip函数将键/值组合
dic = dict(zip('abc', [1, 2, 3]))
>>>>>  {'a': 1, 'b': 2, 'c': 3}
dic = dict(zip(['apple','pen','color'],['red',1,['red','green','blue']]))
>>>>> {'apple': 'red', 'pen': 1, 'color': ['red', 'green', 'blue']}
  • 通过字典推导式创建
dic = {i:2*i for i in range(3)}
>>>>> {0: 0, 1: 2, 2: 4}
  • 所有键的值都相同或者赋予初始值:通过dict.fromkeys()创建,通常用来初始化字典, 设置value的默认值
dic = dict.fromkeys(range(3), 'x')
>>>>> {0: 'x', 1: 'x', 2: 'x'}
7、使用数据结构对真实世界建模
  • 井字棋盘
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ',
            'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ',
            'low-L': ' ', 'low-M': ' ', 'low-R': ' '}
def printBoard(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'])
turn = 'X'
for i in range(9):
    printBoard(theBoard)
    print('Turn for ' + turn + '. Move on which space?')
    move = input()
    theBoard[move] = turn
    if turn == 'X':
        turn = 'O'
    else:
        turn = 'X'
printBoard(theBoard)
8、小项目-好玩游戏的物品清单
def display_inventory(inventory):
    print("Inventory:")
    item_total = 0
    for k, v in inventory.items():
        print(str(v) + ' ' + k)
        item_total += v
    print("Total number of items: " + str(item_total))
def addToInventory(inventory, addedItems):
    for i in addedItems:
        inventory.setdefault(i, 0)
        inventory[i] += 1
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
addToInventory(inv, dragonLoot)
display_inventory(inv)
>>>>> 输出:
Inventory:
45 gold coin
1 rope
1 dagger
1 ruby
Total number of items: 48
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值