Python 字典(dict) 操作基础

曾经终败给现在 2021-12-16 08:34 667阅读 0赞

Python 字典与结构化数据

1.字典基本结构

1.1 创建存储生日的字典

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

1.2 查询生日的小程序

  1. while True:
  2. print('Enter a name(blank to quit):')
  3. name = input()
  4. if name == '':
  5. break
  6. if name in birthday:
  7. print(birthday[name] + 'is the birthday of ' + name)
  8. else:
  9. print("I don't know the birthday of " + name)
  10. print("Tell me plz")
  11. newbday = input()
  12. birthday[name] = newbday
  13. print('Birthday database updated')
  14. Enter a name(blank to quit):
  15. Alice
  16. Ar 1is the birthday of Alice
  17. Enter a name(blank to quit):
  18. Bob
  19. July 7is the birthday of Bob
  20. Enter a name(blank to quit):
  21. Chen
  22. I don't know the birthday of Chen
  23. Tell me plz
  24. July 22th
  25. Birthday database updated
  26. Enter a name(blank to quit):
  27. Chen
  28. July 22this the birthday of Chen
  29. Enter a name(blank to quit):
  30. I don't know the birthday of
  31. Tell me plz
  32. Birthday database updated
  33. Enter a name(blank to quit):
  34. birthday
  35. {'Alice': 'Ar 1', 'Bob': 'July 7', 'Chen': 'July 22th'}
  36. #字典可以修改value,那么,怎么修改key
  37. birthday['Alice'] = 'Apr 1st'
  38. birthday['Bob'] = 'July 7th'
  39. birthday
  40. {'Alice': 'Apr 1st', 'Bob': 'July 7th', 'Chen': 'July 22th'}

2. 字典的方法

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

  1. for v in birthday.values():
  2. print (v)
  3. for v in birthday.keys():
  4. print(v)
  5. for v in birthday.items():
  6. print(v)
  7. Apr 1st
  8. July 7th
  9. July 22th
  10. Alice
  11. Bob
  12. Chen
  13. ('Alice', 'Apr 1st')
  14. ('Bob', 'July 7th')
  15. ('Chen', 'July 22th')
  16. 'Alice' in birthday
  17. 'Apr 1st' in birthday.values()
  18. 'Apr 1st' in birthday.keys()
  19. False

2.2 get方法

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

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

2.3 setdafault() 方法

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

setdefault(‘keys’,’default’)

  1. # 字符统计程序
  2. 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 '
  3. count = {}
  4. for char in message:
  5. count.setdefault(char,0)
  6. count[char] = count[char] + 1
  7. print (count)
  8. {'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 模块

  1. import pprint
  2. pprint.pprint(count)
  3. # 等价于 print(pprint.pformat(count))
  4. {' ': 37,
  5. ',': 1,
  6. '-': 1,
  7. '.': 1,
  8. 'I': 2,
  9. 'a': 12,
  10. 'b': 2,
  11. 'c': 10,
  12. 'd': 4,
  13. 'e': 32,
  14. 'f': 4,
  15. 'g': 2,
  16. 'h': 9,
  17. 'i': 16,
  18. 'k': 2,
  19. 'l': 9,
  20. 'm': 6,
  21. 'n': 26,
  22. 'o': 14,
  23. 'p': 9,
  24. 'r': 10,
  25. 's': 15,
  26. 't': 14,
  27. 'u': 5,
  28. 'v': 1,
  29. 'x': 3,
  30. 'y': 2}

3.小练习

3.1 井字棋

  1. theBoard = {
  2. 'top-l':'' , 'top-m':'' , 'top-r':'',
  3. 'mid-l':'' , 'mid-m':'' , 'mid-r':'',
  4. 'low-l':'' , 'low-m':'' , 'low-r':''}
  5. def printBoard(board):
  6. print(board['top-l'] + ' | ' + board['top-m'] + '| '+board['top-r'])
  7. print('-+-+-')
  8. print(board['mid-l'] + ' | ' + board['mid-m'] + '| '+board['mid-r'])
  9. print('-+-+-')
  10. print(board['low-l'] + ' | ' + board['low-m'] + '| '+board['low-r'])
  11. print('-+-+-')
  12. def gameStart():
  13. printBoard(theBoard)
  14. i = 0
  15. while True:
  16. chess = ['O','X']
  17. print('where do you wanna place')
  18. position = input()
  19. if theBoard[position]:
  20. print('already full')
  21. print('Another choice plz')
  22. position = input()
  23. theBoard[position] = chess[i]
  24. printBoard(theBoard)
  25. i = 1 - i
  26. #判断棋盘是否已满,笨办法
  27. k = 0
  28. for value in theBoard.values():
  29. if value:
  30. k = k+1
  31. if k >=9 :
  32. print('All full,the end')
  33. break

3.2 嵌套的字典和列表

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

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

    allGuests = {

    1. 'Ali':{
    2. 'apple':16,'bread':12},
    3. 'Bob':{
    4. 'ham':1,'coffee':32,'apple':3},
    5. 'Carol':{
    6. 'bread':23,'coffee':2}}

    def totalBrought(guests,item):

    1. numBrought = 0
    2. for k,v in guests.items(): #字典中item的循环 k,v
    3. numBrought = numBrought + v.get(item,0)
    4. 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 好玩游戏的物品清单

  1. stuff = {
  2. 'rope':5,'torch':2,'gold':100,'sword':1}
  3. def inventoryDisplay(stuff):
  4. numTotal = 0
  5. print('Inventory:')
  6. for k,v in stuff.items():
  7. print( k +':'+ str(v))
  8. numTotal = numTotal + v
  9. print ('total:'+ str(numTotal))
  10. #屠龙战利品 以列表形式存储
  11. dragonLoot = ['rope','rope','torch','gold','gold','gold','diamond']
  12. #列表到字典的函数
  13. def addToInventory(loot,stuff):
  14. countLoot = {}
  15. for k in loot:
  16. countLoot.setdefault(k,0)
  17. countLoot[k] = countLoot[k] + 1
  18. for l in countLoot.keys():
  19. stuff.setdefault(l,0)
  20. stuff[l] = stuff[l] + countLoot[l]
  21. return stuff
  22. inventoryDisplay(stuff)
  23. print(addToInventory(dragonLoot,stuff))
  24. Inventory:
  25. rope:5
  26. torch:2
  27. gold:100
  28. sword:1
  29. total:108
  30. {'rope': 7, 'torch': 3, 'gold': 103, 'sword': 1, 'diamond': 1}

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

转载于:https://www.cnblogs.com/blogofnickchen/p/7221634.html

发表评论

表情:
评论列表 (有 0 条评论,667人围观)

还没有评论,来说两句吧...

相关阅读

    相关 pythondict字典

    字典是一系列由键(key)和值(value)配对组成的元素的集合,在 Python3.7+,字典被确定为有序(注意:在 3.6 中,字典有序是一个implementation