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"}}
Dictionaries And Identity Operators_第1张图片
15705531.png

to solved this problem my solution is


Dictionaries And Identity Operators_第2张图片
15860375.png

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

Dictionaries And Identity Operators_第3张图片
16078453.png

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

你可能感兴趣的:(Dictionaries And Identity Operators)