Dictionaries And Identity Operators

Dictionaries

Dictionaries can have keys of any immutable type, like integers or tuples even list, not just strings.

elements = {"hydrogen": 1, "helium": 2, "carbon": 6}# attention mutable can't be used as a key in dictionary
print(elements["helium"])  # print the value mapped to "helium"
elements["lithium"] = 3  # insert "lithium" with a value of 3 into the dictionary
animals = {'dogs': [20, 10, 15, 8, 32, 15], 'cats'(this is the key): [3,4,2,8,2,4](this is the value), 'rabbits': [2, 3, 3], 'fish': [0.3, 0.5, 0.8, 0.3, 1]} # the example of defining the lists as values 
# The result of animals['dogs'][3] is 8

attention mutable can't be used as a key in dictionary

Look Up

print("carbon" in elements)
print(elements.get("dilithium"))
# output:
True
None

Identity Operators

You can check if a key returned None with the is operator. You can check for the opposite using is not.

n = elements.get("dilithium")
print(n is None)
print(n is not None)

Compound Data Structures In Dictionary

Defined

elements = {"hydrogen": {"number": 1,
                         "weight": 1.00794,
                         "symbol": "H"},
              "helium": {"number": 2,
                         "weight": 4.002602,
                         "symbol": "He"}}

Access Elements

helium = elements["helium"]  # get the helium dictionary
hydrogen_weight = elements["hydrogen"]["weight"]  # get hydrogen's weight

Add

oxygen = {"number":8,"weight":15.999,"symbol":"O"}  # create a new oxygen dictionary 
elements["oxygen"] = oxygen  # assign 'oxygen' as a key to the elements dictionary
print('elements = ', elements)
# output:
elements =  {"hydrogen": {"number": 1,
                          "weight": 1.00794,
                          "symbol": 'H'},
               "helium": {"number": 2,
                          "weight": 4.002602,
                          "symbol": "He"}, 
               "oxygen": {"number": 8, 
                          "weight": 15.999, 
                          "symbol": "O"}}
15705531.png

to solved this problem my solution is


15860375.png

remember boolean is also can be a value in dictionary
so the anwser is

16078453.png

the nature of boolean is integer "1" and "0"

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,490评论 0 10
  • 今天看了《谁的青春不迷茫》的宣传,感慨自然很多。最后最多的竟然是对于《变形记》的感触。 对于这个电影,包括这本书,...
    鸵鸟变凤凰阅读 566评论 2 1
  • ① 前段时间买了几本书,里面包括...
    栖小熊阅读 201评论 1 2
  • 5月的最后第2天了,马上要过六一了,小朋友为什么总是高高兴兴的?就是有一颗童心! 不忘初心,重要的是保持童心! 周...
    天使小鱼儿阅读 676评论 6 8
  • 弟弟买了一个雪橇,带着侄儿去滑雪,看得我女儿眼馋,嚷着让我陪她一起去玩。今天下午的时间就全部贡献给了孩子们。 说实...
    一路修行ld阅读 194评论 0 1