Python基础---dict(字典)

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):

 

 

上一篇:2021/6/4--python学习记录


下一篇:python学习(day2)