欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python基础---Dict(字典)

程序员文章站 2022-07-15 07:59:28
...

1.字典以键值对组成,包含在{}中,字典的键必须为hashable,即不可变(字符串、元组、数字),并且唯一;值可以是任何类型

# dict1 = {[1]: 1}  # 报错:TypeError: unhashable type: 'list'

# dict1 = {{1}: 1}  # 报错:TypeError: unhashable type: 'set'

dict1 = {(1,): 1}
print(dict1)  # {(1,): 1}

dict1 = {"12": 122}
print(dict1)  # {'12': 122}

dict1 = {1: 12}
print(dict1)  # {1: 12}

2.字典的创建有多种,以下几种都等同

dict1 = dict(one=1, two=2)
print(dict1)  # {'one': 1, 'two': 2}

dict2={"one":1,"two":2}
print(dict2)  # {'one': 1, 'two': 2}

dict3=dict(zip(["one","two"],[1,2]))
print(dict3)  # {'one': 1, 'two': 2}

dict4=dict( (("one",1),("two",2)) )
print(dict4)  # {'one': 1, 'two': 2}

dict5=dict( [("one",1),("two",2)] )
print(dict4)  # {'one': 1, 'two': 2}

dict6=dict({"one":1,"two":2})
print(dict6)  # {'one': 1, 'two': 2}

print(dict1==dict2==dict3==dict4==dict5==dict6)  # True

3.键用数字的时候,像1和1.0、1.00都是相同的,可以用来索引同一个字典条目,如果相同的键出现多次,则以最后的值为准

dict1 = {1: 12}
print(dict1)  # {1: 12}

dict1 = {1: 12, 1.0: 33}
print(dict1)  # {1: 33}

dict1 = {1: 12, 1.0: 33,1.00:666}
print(dict1)  # {1: 666}

4.len(dict):表示字典中元素的个数

dict1 = {"a": 1, "aa": 11}
print(len(dict1))  # 2

dict1 = {"a": 1, "aa": 11,"b":2,"bb":22}
print(len(dict1))  # 4

5.dict[key]:返回 dict 中以 key 为键的值, 如果key不存在 , 则会引发 KeyError

dict1 = {"a": 1, "aa": 11,"b":2,"bb":22}
print(dict1["aa"])  # 11
# print(dict1["c"])  # 报错:KeyError: 'c'