python学习5

Python-dictionary

dictionary and import

1
2
3
spam={'name':'Zophie','age':7}
spam['name']
#out:'Zophie'

values&keys&items

1
2
3
4
5
6
7
spam={'color':'red','age':'42'}
for v in spam.values():
print(v)
for k in spam.keys():
print(k)
for i in spam.items():
print(i)

out:

red

42

color

age

(‘color’, ‘red’)

(‘age’, ‘42’)

use the factor in dictionary to form list

1
2
3
spam={'color':'red','age':'42'}
list(spam.keys())
#out:['color', 'age']

use the factors in items at the same time

1
2
3
spam={'color':'red','age':'42'}
for k,v in spam.items():
print('Key: '+k+' Value: '+str(v))

out:

Key: color Value: red
Key: age Value: 42

use the keys to find the values

1
2
3
numbers={'one':1,'two':2,'three':3}
print(numbers['two'])
#out:2

but values can’t be used to find keys

1
2
numbers={"one": 1, "two": 2}
print (numbers[2])
1
2
3
4
5
6
7
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-1-d797711df7b1> in <module>
1 numbers={"one": 1, "two": 2}
----> 2 print (numbers[2])

KeyError: 2

use with sort

1
2
3
4
5
numbers={"one": 1, "two": [4, 6, 3], "three": 3}
x = (numbers["two"])
print(x)
x.sort()
print(x)

out:

[4, 6, 3]
[3, 4, 6]

use pop to delete items

1
2
3
4
numbers={1: 2, 3:4}
numbers.pop(3)
print (numbers)
#out:{1: 2}

use get to get values

1
2
3
d={"uno":["one",1],"dos":["two",2]}
d.get("uno")
#out:['one', 1]

if there is no key

1
2
3
d={"uno":["one",1],"dos":["two",2]}
print (d.get(3,'cat'))
#out:cat

example for dictionary

1
2
3
4
5
6
7
8
9
10
k=input()
v1=int(input())
v2=int(input())
v3=int(input())
d={k:(v1,v2,v3)}
if v1>=78 and v2>=78 and v3>=78:
for i in d.items():
print(i)
else:
print('not pass')

out:

Jim Jim
78 90
76 78
90 80
not pass (‘Jim’, (90, 78, 80))

use setdefault to add items to dictionary

1
2
3
4
5
spam={'name':'Pooka','age':5}
spam.setdefault('color','black')
spam
spam.setdefault('color','white')
spam

out: {‘name’: ‘Pooka’, ‘age’: 5, ‘color’: ‘black’}

1
2
3
4
5
6
message='It was a bright cold day in April,and the clocks were striking thirtheen.'
count={}
for character in message:
count.setdefault(character,0)#creat the items for counting the number
count[character]=count[character]+1#add one more to count
print(count)

out: {‘I’: 1, ‘t’: 6, ‘ ‘: 12, ‘w’: 2, ‘a’: 4, ‘s’: 3, ‘b’: 1, ‘r’: 5, ‘i’: 6, ‘g’: 2, ‘h’: 4, ‘c’: 3, ‘o’: 2, ‘l’: 3, ‘d’: 3, ‘y’: 1, ‘n’: 4, ‘A’: 1, ‘p’: 1, ‘,’: 1, ‘e’: 5, ‘k’: 2, ‘.’: 1}

use of pprint

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import pprint
score=[90,89,80,77,89,77,90,81,82,76,89]
result={}
for i in score:
if i>=90:
result.setdefault('A*',0) #if there is no value, the value is 0
result['A*']=result['A*']+1
if i>=75 and i<90:
result.setdefault('A',0)
result['A']=result['A']+1
if i>=60 and i<75:
result.setdefault('B',0)
result['B']=result['B']+1
pprint.pprint(result)

out:{‘A’: 9, ‘A*’: 2}

used in game:

create background

1
2
3
4
5
6
7
8
9
10
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ',
'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ',
'low-L': ' ', 'low-M': ' ', 'low-R': ' '} #create dictionary to record the value
def printBoard(board):
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R']) #put the records in the background
print('-+-+-') #separate the rows
print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
print('-+-+-')
print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])
printBoard(theBoard)

| |
-+-+-
| |
-+-+-
| |

1
2
3
4
5
6
7
8
9
theBoard = {'top-L': 'O', 'top-M': 'O', 'top-R': 'O', 'mid-L': 'X', 'mid-M':
'X', 'mid-R': ' ', 'low-L': ' ', 'low-M': ' ', 'low-R': 'X'}
def printBoard(board): #make the printing processes a function
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'])
printBoard(theBoard)

O|O|O
-+-+-
X|X|
-+-+-
| |X

1
2
3
4
5
6
7
8
9
10
11
turn = 'X'
for i in range(9):
printBoard(theBoard) #the function
print('Turn for ' + turn + '. Move on which space?')
move = input()
theBoard[move] = turn
if turn == 'X':
turn = 'O'
else:
turn = 'X'
printBoard(theBoard)

O|O|O
-+-+-
X|X|
-+-+-
| |X
Turn for X. Move on which space?
top-L
X|O|O
-+-+-
X|X|
-+-+-
| |X

… …

another example to record the number:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
allGuests={'Alice':{'apples':5,'pretzels':12},
'Bob':{'ham sandwiches':3,'apples':2},
'Carol':{'cups':3,'apple pies':1}}
def totalBrought(guests,item):
numBrought=0
for k,v in guests.items():
numBrought=numBrought+v.get(item,0)
return numBrought
print('Number of things being brought:')
print(' - Apples ' + str(totalBrought(allGuests, 'apples')))
print(' - Cups ' + str(totalBrought(allGuests, 'cups')))
print(' - Cakes ' + str(totalBrought(allGuests, 'cakes')))
print(' - Ham Sandwiches ' + str(totalBrought(allGuests, 'ham sandwiches')))
print(' - Apple Pies ' + str(totalBrought(allGuests, 'apple pies')))

Number of things being brought:

  • Apples 7
  • Cups 3
  • Cakes 0
  • Ham Sandwiches 3
  • Apple Pies 1