The dictionary

Dictionary creation

Dict1 = {" zhang SAN ": 20, "Li Si ": 30} print (dict1) # use dict function creates dict1 = dict (name = "zhangsan", the age = 18) print (dict1) # create an empty dictionary dict1 = {} print (dict1)Copy the code

Get the dictionary element

Dict1 = {" zhang SAN ": 20," bill ": 30} # use [] to obtain, no key return behind KeyError print (dict1 [" zhang SAN"]) # # 20 print (dict1 [" detective "]) # KeyError: Dict1. Get (" dict2 ")) # 4 print(dict1. Get (" dict3 ")) # 4 print(dict1. If no, return the default valueCopy the code

Add, delete, modify and check the dictionary

# dictdict1 = {" zhang SAN ": 20, "Li Si ": 4} print(" dict1 "in dict1) # True print(" dict2" not in dict1) # False # Dict1 [" dict3 "] the dict2 # {' dict3 ': 0} # Dict1 = {" dict3 ": 23, "dict4 ": {" dict1" = {" dict1 ": 30} Dict1 [" dict2 "] = 0 print(dict1) # {} # Dictatorial 1. Dictatorial () print(type(keys)) print(list(keys)) # dictatorial 1 = {" 女 三": 23, "女 四": 30} values = dict1. Values () print (values) print (type (values) print (list (values) # get dictionary all key/value pair dict1 = {" zhang SAN ": 20," bill ": 30} items = dict1.items() print(items) print(type(items)) print(list(items))Copy the code

Dictionary element traversal

Dict1 = {" dict3 ": 20, "dict4 ": 30} for item in dict1: print(item, dict1[item], dict1. Get (item))Copy the code

Dictionary keys must be immutable objects

List1 = [100, 200] dict1 = {"key1": 10, "key2": 20} # dict1 = {list1: 30} # TypeError: unhashable type: 'list' print(dict1)Copy the code

Dictionary generation

# dictionary generation; Dict1 = ["k1", "k2", "k3"] value1 = [10, 20, 30] dict1 = {my_key: my_value for my_key, my_value in zip(key1, value1)} print(dict1)Copy the code