1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| print("--------------- 字典基本操作 ---------------") person1 = {"first_name": "Aaron", "last_name": "Zhu", "age":18}
print("person key-value nums:", len(person1))
print("person1 -> last_name :", person1["last_name"]) print("person1 -> age :", person1["age"]) try: print("person1 phone number: ", person1["phone_number"]) except Exception as e: print("Happen Exception: ", e)
print("person1 first name: ", person1.get("first_name")) print("person1 first name: ", person1.get("first_name","Tony")) print("person1 phone number: ", person1.get("phone_number")) print("person1 phone number: ", person1.get("phone_number", "110"))
print("key age in person1 : ", "age" in person1) print("key Aaron in person1 : ", "Aaron" in person1) print("key my_age not in person1 : ", "my_age" not in person1)
person1["last_name"] = "Wang"
person1["sex"] = "man" print("after modify person1:",person1)
del person1["first_name"] print("after del first name, person1:",person1)
my_age = person1.pop("age") print("my_age:",my_age) print("after del age, person1:",person1)
kv_tuple = person1.popitem() print("after del random key-value, person1:",person1) print("kv tuple:", kv_tuple)
person1.clear() print("after clear person1:",person1)
|