Python 字典(dict) 操作基础

Python 字典与结构化数据

1.字典基本结构

1.1 创建存储生日的字典

birthday = {'Alice':'Ar 1','Bob':'July 7'}

1.2 查询生日的小程序

while True:
    print('Enter a name(blank to quit):')
    name = input()
    if name == '':
        break

    if name in birthday:
        print(birthday[name] + 'is the birthday of ' + name)
    else:
        print("I don't know the birthday of " + name)
        print("Tell me plz")
        newbday = input()
        birthday[name] = newbday
        print('Birthday database updated')
Enter a name(blank to quit):
Alice
Ar 1is the birthday of Alice
Enter a name(blank to quit):
Bob
July 7is the birthday of Bob
Enter a name(blank to quit):
Chen
I don't know the birthday of Chen
Tell me plz
July 22th
Birthday database updated
Enter a name(blank to quit):
Chen
July 22this the birthday of Chen
Enter a name(blank to quit):

I don't know the birthday of  
Tell me plz

Birthday database updated
Enter a name(blank to quit):
birthday
{'Alice': 'Ar 1', 'Bob': 'July 7', 'Chen': 'July 22th'}
#字典可以修改value,那么,怎么修改key
birthday['Alice'] = 'Apr 1st'
birthday['Bob'] = 'July 7th'
birthday
{'Alice': 'Apr 1st', 'Bob': 'July 7th', 'Chen': 'July 22th'}

2. 字典的方法

2.1 字典的 values() , keys() ,items()

for v in birthday.values():
    print (v)
for v in birthday.keys():
    print(v)
for v in birthday.items():
    print(v)
Apr 1st
July 7th
July 22th
Alice
Bob
Chen
('Alice', 'Apr 1st')
('Bob', 'July 7th')
('Chen', 'July 22th')
'Alice' in birthday
'Apr 1st' in birthday.values()
'Apr 1st' in birthday.keys()
False

2.2 get方法

有对应键,返回键对应值;没有对应键存在,返回备用值


print('I think Rachel was born on '+ birthday.get('Rachel','a rainy day'))
I think Rachel was born on a rainy day

2.3 setdafault() 方法

为键赋予默认取值,返回 键的当前值;

setdefault(‘keys’,’default’)


# 字符统计程序
message = 'In the preceding example, the kernel is chosen 
because it represents an expansion of polynomials and can conveniently compute 
high-dimensional inner products. In this example the kernel is chosen 
because of its functional form in the representation '

count = {}
for char in message:
    count.setdefault(char,0)
    count[char] = count[char] + 1

print (count)
{'I': 2, 'n': 26, ' ': 37, 't': 14, 'h': 9, 'e': 32, 'p': 9, 'r': 10, 'c': 10, 'd': 4, 'i': 16, 'g': 2, 'x': 3, 'a': 12, 'm': 6, 'l': 9, ',': 1, 'k': 2, 's': 15, 'o': 14, 'b': 2, 'u': 5, 'f': 4, 'y': 2, 'v': 1, '-': 1, '.': 1}

2.4 漂亮打印 pprint 模块


import pprint
pprint.pprint(count)

# 等价于 print(pprint.pformat(count))
{' ': 37,
 ',': 1,
 '-': 1,
 '.': 1,
 'I': 2,
 'a': 12,
 'b': 2,
 'c': 10,
 'd': 4,
 'e': 32,
 'f': 4,
 'g': 2,
 'h': 9,
 'i': 16,
 'k': 2,
 'l': 9,
 'm': 6,
 'n': 26,
 'o': 14,
 'p': 9,
 'r': 10,
 's': 15,
 't': 14,
 'u': 5,
 'v': 1,
 'x': 3,
 'y': 2}

3.小练习

3.1 井字棋


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'])
    print('-+-+-')

def gameStart():
    printBoard(theBoard)
    i = 0
    while True:
        chess = ['O','X']

        print('where do you wanna place')
        position = input()
        if theBoard[position]:
            print('already full')
            print('Another choice plz')
            position = input()

        theBoard[position] = chess[i]
        printBoard(theBoard)
        i = 1 - i
        #判断棋盘是否已满,笨办法
        k = 0
        for value in theBoard.values():
            if value:
                k = k+1

        if k >=9 :
            print('All full,the end')
            break

3.2 嵌套的字典和列表

  • 对复杂事物进行建模,字典列表中可能包含其他字典列表;
  • 列表适合包含一组有序的值,字典适合包含关联的键和值

#示例程序:统计野餐事物总数

allGuests = {'Ali':{'apple':16,'bread':12},
             'Bob':{'ham':1,'coffee':32,'apple':3},
            'Carol':{'bread':23,'coffee':2}}

def totalBrought(guests,item):
    numBrought = 0
    for k,v in guests.items():                   #字典中item的循环 k,v
        numBrought = numBrought + v.get(item,0)
    return numBrought

print('Number of things being brought:')
print('- apples :'+ str(totalBrought(allGuests,'apple')))
print('- bread :' + str(totalBrought(allGuests,'bread')))
print('- coffee :'+ str(totalBrought(allGuests,'coffee')))
Number of things being brought:
- apples :19
- bread :35
- coffee :34

3.3 好玩游戏的物品清单

stuff = {'rope':5,'torch':2,'gold':100,'sword':1}

def inventoryDisplay(stuff):
    numTotal = 0
    print('Inventory:')
    for k,v in stuff.items():
        print( k +':'+ str(v))
        numTotal = numTotal + v
    print ('total:'+ str(numTotal))

#屠龙战利品 以列表形式存储
dragonLoot = ['rope','rope','torch','gold','gold','gold','diamond']

#列表到字典的函数
def addToInventory(loot,stuff):
    countLoot = {}
    for k in loot:
        countLoot.setdefault(k,0)
        countLoot[k] = countLoot[k] + 1
    for l in countLoot.keys():
        stuff.setdefault(l,0)
        stuff[l] = stuff[l] + countLoot[l]
    return stuff


inventoryDisplay(stuff)
print(addToInventory(dragonLoot,stuff))
Inventory:
rope:5
torch:2
gold:100
sword:1
total:108
{'rope': 7, 'torch': 3, 'gold': 103, 'sword': 1, 'diamond': 1}

参考文献
《Python编程快速上手–让繁琐工作自动化》

原文地址:https://www.cnblogs.com/blogofnickchen/p/7221634.html