1.Dictionaries
purse = dict()
purse['money'] = 12
purse[''candy] = 3
purse['tissues'] = 75
print (purse)
>>> ['money':12, 'tissues': 75,'candy':3]
2. get method for dictionaries
counts = dict()
names = ['csev','cwen','csev','zqian','cwen']
for name in names:
counts[name] = counts.get(name,0) +1
print(counts)
3.Program
//计算文中单词出现的频数
counts = dict()
print ('Enter a line of text:')
line = input("")
words = line.split()
print ('Words:',words)
print ('Counting')
for name in words:
counts[name] = counts.get(name,0) +1
print ('Counts',counts)
4. for loop in dictionaries
counts = ('chuck':1,'fred':42,'jan':100)
for key in counts:
print (key,counts[key])
>>> jan 100
>>> chuck 1
>>> fred 42
5. Retrieving lists of Keys and Values
jjj = {'chuck':1,'fred':42,'jan':100}
print (list(jjj))
>>> ['jan','chuck','fred']
print (jjj.keys())
>>> ['jan','chuck','fred']
print (jjj.values())
>>> [100,1,42]
print (jjj.items())
>>> [('jan',100),('chuck',1),('fred',42)]
6.Two Iteration Variables!
jjj = {'','',''}
for aaa,bbb in jjj.items():
print(aaa,bbb)
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
planet_to_initial = {planet: planet[0] for planet in planets}
planet_to_initial
>>> {'Earth': 'E',
'Jupiter': 'J',
'Mars': 'M',
'Mercury': 'M',b
'Neptune': 'N',
'Saturn': 'S',
'Uranus': 'U',
'Venus': 'V'}