import numpy as ny
print('change List to Dict')
stuff={'rope':1,'torch':1,'gold coin':42,'dagger':1,'arrow':12}
stuff1={'rope':1,'torch':1,'gold coin':42,'dagger':1,'arrow':12}
dragon=['gold coin','gold coin','dagger','gold coin','ruby',
'gold coin','gold coin','dagger','gold coin','ruby']
def displaynum(invertory):
for i,j in invertory.items():
# print(str(j)+' '+str(i))
print(j,i)
def addnum(invertory1,list1):
for i in range(len(list1)):
if list1[i] in invertory1.keys():
invertory1[list1[i]]+=1
else:
invertory1.setdefault(list1[i],1)
return invertory1
def addnum1(invertory1,list1):
for i in range(len(list1)):
invertory1.setdefault(list1[i],0)
invertory1[list1[i]]+=1
return invertory1
print('the first method')
displaynum(addnum(stuff,dragon))
print('the second method')
displaynum(addnum1(stuff1,dragon))
#5.6.1和5.6.2的参考代码import numpy as nyprint('change List to Dict')stuff={'rope':1,'torch':1,'gold coin':42,'dagger':1,'arrow':12}stuff1={'rope':1,'torch':1,'gold coin':42,'dagger':1,'arrow':12}dragon...