1.setdefault()方法语法
dict.setdefault(key, default=None)
说明:如果字典中包含给定的键值,那么返回该键对应的值。否则,则返回给定的默认值。
Syntax: dict.setdefault(key, default_value) Parameters: It takes two parameters: key – Key to be searched in the dictionary. default_value (optional) – Key with a value default_value is inserted to the dictionary if key is not in the dictionary. If not provided, the default_value will be None. Returns: Value of the key if it is in the dictionary. None if key is not in the dictionary and default_value is not specified. default_value if key is not in the dictionary and default_value is specified.
2.append()方法语法
list.append(obj)
说明:在列表末尾添加新的对象,无返回值,会修改原来的列表。
3.测试示例:
if __name__ == "__main__": name = "ZhangSan" age = 20 new_datasets = {} new_datasets.setdefault(name, []) print(new_datasets)
返回:{'ZhangSan': []}
说明:因为"ZhangSan"在集合new_datasets中不存在,结果返回键值对,键对应的值的值是默认值[]。
if __name__ == "__main__": name = "ZhangSan" age = 20 new_datasets = {} new_datasets.setdefault(name, []).append(age) print(new_datasets)
返回:{'ZhangSan': [20]}
说明:因为"ZhangSan"在集合new_datasets中不存在,结果返回键值对,键对应的值的值是默认值[]。则返回默认值[],接着又对空列表进行操作,在空列表中添加age。