js css htmlpython入门

字典函数

2022-06-06  本文已影响0人  朱兰Juran

字典

就像列表一样,字典键可以被分配到不同的值。

但是,与列表不同,新的字典键也可以被赋值,而不仅仅是已经存在的字典键。

例如:

squares = {1: 1, 2: 4, 3: "error", 4: 16,}

squares[8] = 64

squares[3] = 9

print(squares)

结果:

{8: 64, 1: 1, 2: 4, 3: 9, 4: 16}


字典 - in 和 not

要确定 key (键)是否在字典中,您可以使用 in 和 not,就像你可以使用列表一样。

例如:

nums = {

  1: "one",

  2: "two",

  3: "three",

}

print(1 in nums)

print("three" in nums)

print(4 not in nums)

结果:

True

False

True


字典- get

一个很有用的字典方法是 get 。它与索引做同样的事情,但是如果在字典中找不到键,它将返回另一个指定的值(默认情况下为“None”)。

例如:

pairs = {1: "apple",

  "orange": [2, 3, 4],

  True: False,

  None: "True",

}

print(pairs.get("orange"))

print(pairs.get(7))

print(pairs.get(12345, "not in dictionary"))

结果:

[2, 3, 4]

None

not in dictionary

上一篇 下一篇

猜你喜欢

热点阅读