字典语法

146 阅读1分钟

{key:value, ... ...}key必须可哈希(唯一)

1、转化

#列表或者元组中每个元素必须为列表或者元组且长度为2
phoneprice = [['小米8青春版',1699], ['华为P20',3188], ['VIVOX23', '2798']]
pdict = dict(phoneprice)
print(pdict)                      #列表转化为字典dict

2、fromkeys方法

#字符串 
kstr = 'abcd'
dstr = dict.fromkeys(kstr, 1)
print('dstr:',dstr)
#列表:
klist = ['python','java','C++']
dlist = dict.fromkeys(klist, 0)
print(dlist)    #字典初始化常用的方式。

3、常用方法

获取key 与 元素值等