Python 基本數據類型基礎實戰【字典(哈希表)】

#統計字母頻
import string
import random
import collections
y = collections.OrderedDict() #有序字典
y = collections.Counter() #更加快速的統計出現次數最多的元素

x = string.ascii_letters + string.digits
z = ''.join((random.choice(x) for i in range(1000)))
d = dict()
for ch in z:
    d[ch] = d.get(ch,0) + 1
for k , v in sorted(d.items()):
    print(k,":",v)


#pop() popitem() del clear() 用於刪除
#Answer:
#0 : 18
#1 : 16
#2 : 13
#3 : 16
#4 : 17
#5 : 20
#6 : 18
#7 : 18
#8 : 20
#9 : 16
#A : 19
#B : 15
#C : 19
#D : 20
#E : 14
#F : 19
#G : 13
#H : 19
#I : 13
#J : 13
#K : 14
#L : 10
#M : 19
#N : 13
#O : 14
#P : 28
#Q : 23
#R : 11
#S : 16
#T : 11
#U : 15
#V : 24
#W : 24
#X : 16
#Y : 16
#Z : 16
#a : 18
#b : 16
#c : 17
#d : 12
#e : 16
#f : 11
#g : 15
#h : 14
#i : 21
#j : 16
#k : 20
#l : 16
#m : 18
#n : 22
#o : 10
#p : 12
#q : 17
#r : 9
#s : 13
#t : 14
#u : 13
#v : 15
#w : 15
#x : 17
#y : 12
#z : 15






# dictionary
# Python字典通過哈希表實現

x = dict()
x = {}
keys = ['a','b','c','d']
values = [1,2,3,4]
dictionary = dict (zip (keys , values))
print(dictionary)
#for i in range(1,4):
#    print(dictionary[i])

#Answer:
#{'a': 1, 'b': 2, 'c': 3, 'd': 4}


#字典元素訪問
if '10' in dictionary:
    print(dictionary['10'])
else:
    print("Not Exists!")
#Answer:
#Not Exists!
#防止被拋出異常,最好先使用類似於find的操作

#字典訪問機制1

for key in dictionary:
    print(key,dictionary[key],keys,values)

#Answer:values後加,可以使得最後一個元素後接空格
#a 1 ['a', 'b', 'c', 'd'] [1, 2, 3, 4]
#b 2 ['a', 'b', 'c', 'd'] [1, 2, 3, 4]
#c 3 ['a', 'b', 'c', 'd'] [1, 2, 3, 4]
#d 4 ['a', 'b', 'c', 'd'] [1, 2, 3, 4]

for i in dictionary:
    print(i+str(dictionary[i]))
#Answer 
#a1
#b2
#c3
#d4

#字典訪問機制2

for k,v in dictionary.items():
    print(k,v)
    

#Answer:items返回的是列表對象
#a 1
#b 2
#c 3
#d 4

for k,v in dictionary.items():
    print(type(k),type(v))

#Answer:
#<class 'str'> <class 'int'>
#<class 'str'> <class 'int'>
#<class 'str'> <class 'int'>
#<class 'str'> <class 'int'>


#for k,v in dictionary.iteritems(): 該方法已被PY3刪除!
#    print(k,v)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章