python3中的字典

2021-09-27 10:12:14 字數 1273 閱讀 2212

#字典是一種對映,

eng2sp =

dict()

print

(eng2sp)

eng2sp[

"one"]=

'undo'

print

(eng2sp)

eng2sp[

'two']=

'df'

print

(eng2sp)

d=eng2sp[

'one'

]print

(d)###########字典中的順序是不可預料的

a=len

(eng2sp)

#顯示鍵值對的個數

print

(a)#####判定乙個值是不是字典中的鍵

if'one'

in eng2sp:

print

(true

)'undo'

in eng2sp

##########使用values方法,返回乙個值的集合

vals = eng2sp.values(

)print

(vals)

########使用字典作為計數器的集合

defhistogram

(s):

d =dict()

for c in s:

if c not

in d:

d[c]=1

else

: d[c]+=1

return

(d)s =

"skdfdshfkshdfhsdjgajdhfkhdskjf"

js = histogram(s)

print

(js)

######get方法,如果鍵出現在字典中,get返回對應值,否則返回預設值

h = histogram(

'a')

c = h.get(

'a',0)

print

(c)d = h.get(

'b',0)

print

(d)########

defprint_hist

(h):

for c in h:

print

(c,h[c]

,end=

" "

)h = histogram(

"parrot"

)print

(print_hist(h)

)

python3字典詳解 python3中字典詳解

字典 dict 1.建立字典的幾種方式 class dict kwarg class dict iterable,kwarg 使用上面的方法構建字典 方法1構建字典 a dict one 1,two 2,three 3 a輸出結果 方法2構建字典 a dict a輸出結果 方法3構建字典 d dic...

python3中字典key取值

python2中,使用keys 可以得到該字典的所有鍵值,結果以list形式進行表示,可以採用下標方式進行選取第n個鍵值。如下 python2 a a.keys 1,2,4,6 a.keys 2 4 type a.keys list 但是,在python3中,由於資料結構發生了變化,不能夠再直接採用...

Python3 中對字典排序

當然,python3 中的字典 dict 和集合 set 類似,都是沒有所謂順序的,但是你肯定有過這樣的需求 怎麼讓 python3 中的字典按照鍵的順序重新排列得到新的字典呢?下面就給你展示一下吧!dict test dict sorted dict test.items key lambda x...