字典:
- 字典是一种组合数据,没有顺序的组合数据,数据以键值对形式出现spa
# 字典的建立 # 建立空字典1 d = {} # 建立空字典2 d = dict() # 建立有值的字典,每一组数据用冒号隔开,每一对键值对用逗号隔开 d = {"one":1, "two":2, "three":3} # 用dict建立有内容字典1 d = dict({"one":1, "two":2, "three":3}) # 用关键字参数建立有内容字典2 d = dict(one=1, two=2, three=3) # 用tuple建立有内容字典3 d = dict( [("one",1), ("two",2), ("three",3)])
- 字典是序列类型,可是是无序序列,因此没有分片和索引
- 字典中的数据每一个都有键值对组成,即kv对
- key: 必须是可哈希的值,好比int,string,float,tuple 可是list,set,dict 不行
- value: 任何值code
# 访问数据 d = {"one":1, "two":2, "three":3} # 注意访问格式,中括号内是键值 print(d["one"]) d["one"] = "eins" print(d) # 使用del删除某个键值对 del d["one"] print(d) #1 #{'one': 'eins', 'two': 2, 'three': 3} #{'two': 2, 'three': 3}
# 成员检测, in, not in # 成员检测检测的是key内容 d = {"one":1, "two":2, "three":3} if 2 in d: print("value") if "two" in d: print("key") if ("two",2) in d: print("kv") #key
d = {"one":1, "two":2, "three":3} # 使用for循环,直接按key值访问 for k in d: print(k, d[k]) # 上述代码能够改写成以下 for k in d.keys(): print(k, d[k]) # 只访问字典的值 for v in d.values(): print(v) # 注意如下特殊用法 for k,v in d.items(): print(k,'--',v) #one 1 #two 2 #three 3 #one 1 #two 2 #three 3 #1 #2 #3 #one -- 1 #two -- 2 #three -- 3
d = {"one":1, "two":2, "three":3} # 常规字典生成式 dd = {k:v for k,v in d.items()} print(dd) # 加限制条件的字典生成式 dd = {k:v for k,v in d.items() if v % 2 == 0} print(dd) #{'one': 1, 'two': 2, 'three': 3} #{'two': 2}
# items: 返回字典的键值对组成的元组格式 d = {"one":1, "two":2, "three":3} i = d.items() print(type(i)) print(i) #<class 'dict_items'> #dict_items([('one', 1), ('two', 2), ('three', 3)])
# keys:返回字典的键组成的一个结构 k = d.keys() print(type(k)) print(k) #<class 'dict_keys'> #dict_keys(['one', 'two', 'three'])
# values: 返回字典的键值组成的一个结构 v = d.values() print(type(v)) print(v) #<class 'dict_values'> #dict_values([1, 2, 3])
# get: 根据制定键返回相应的值, 好处是能够设置默认值 d = {"one":1, "two":2, "three":3} print(d.get("on333")) # get默认值是None,能够设置,找到则输出没找到则返回100 print(d.get("one", 100)) print(d.get("one333", 100)) #print(d['on333'])程序会直接报错 #None #1 #100
# fromkeys: 使用指定的序列做为键,使用一个值做为字典的全部的键的值 l = ["eins", "zwei", "drei"] # 注意fromkeys两个参数的类型和调用主体 d = dict.fromkeys(l, "hahahahahah") print(d) #{'eins': 'hahahahahah', 'zwei': 'hahahahahah', 'drei': 'hahahahahah'}