1. 程式人生 > >[python3] dict字典

[python3] dict字典

字典dict的用法

#!/usr/bin/env python3
#-*- coding: utf-8 -*-
name='zsy'
password = '123'
dictKV = {'zsy':'123','aaa':'456','bbb':'789'}
a = dictKV.items()
print(".item=",a)   #.item= dict_items([('zsy', '123'), ('aaa', '456'), ('bbb', '789')])

b = dictKV.keys()
print(".keys=",b)   #.keys= dict_keys(['zsy', 'aaa', 'bbb'])
c = dictKV.values()
print(".values=",c) #.values= dict_values(['123', '456', '789'])

if name in b:
    print('ok')   #ok

if password == dictKV[name]:
    print('yes')  #yes

ar=[1,2,3,4,5]
d = dict.fromkeys(ar)               #d= {1: None, 2: None, 3: None, 4: None, 5: None}
d1 = dict.fromkeys([1,2,3],'zsy')   #d1= {1: 'zsy', 2: 'zsy', 3: 'zsy'}
d2 = dict.fromkeys(dictKV,'zzz')    #d2= {'zsy': 'zzz', 'aaa': 'zzz', 'bbb': 'zzz'}
d3 = dict.fromkeys(ar,'[one,two]')  #d3= {1: '[one,two]', 2: '[one,two]', 3: '[one,two]', 4: '[one,two]', 5: '[one,two]'}

dictKV.clear()    # 清空詞典所有條目
print(dictKV)     #{}
del dictKV        # 刪除詞典
print(dictKV)     #NameError: name 'dictKV' is not defined