一、字典
1、字典的初始化
字典是一种key-value结构
In [160]: d = {} In [161]: type(d) Out[161]: dict In [166]: d = {‘a‘:1, ‘b‘:2} In [167]: d Out[167]: {‘a‘: 1, ‘b‘: 2} In [180]: d = dict({"a":0, "b":1}) In [181]: d Out[181]: {‘a‘: 0, ‘b‘: 1} In [164]: d = dict([["a", 1], ["b", 2]]) # 可迭代对象的元素必须是一个二元组 In [165]: d Out[165]: {‘a‘: 1, ‘b‘: 2} In [168]: d = dict.fromkeys(range(5)) # 传入的可迭代元素为key,值为None In [169]: d Out[169]: {0: None, 1: None, 2: None, 3: None, 4: None} In [170]: d = dict.fromkeys(range(5), "abc") # 传入的可迭代元素为key,值为abc In [171]: d Out[171]: {0: ‘abc‘, 1: ‘abc‘, 2: ‘abc‘, 3: ‘abc‘, 4: ‘abc‘}
二、字典的基本操作
1、增
In [173]: d = {‘a‘:1, ‘b‘:2} # 直接使用key做为索引,对某个不存在的索引赋值会增加KV对 In [174]: d["c"] = 1 In [175]: d Out[175]: {‘a‘: 1, ‘b‘: 2, ‘c‘: 1} In [175]: d Out[175]: {‘a‘: 1, ‘b‘: 2, ‘c‘: 1} In [176]: d["b"] = 1 In [177]: d Out[177]: {‘a‘: 1, ‘b‘: 1, ‘c‘: 1} ## dict.update() In [178]: d.update((("d", 4),("e", 5))) In [179]: d Out[179]: {‘a‘: 1, ‘b‘: 1, ‘c‘: 1, ‘d‘: 4, ‘e‘: 5}
时间: 2024-11-05 09:52:34