目录
dict方法的使用
clear(…)
D.clear() -> None. Remove all items from D.
删除字典中的所有元素
dict_var = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
dict_var.clear()
print(dict_var)
copy(…)
D.copy() -> a shallow copy of D
返回字典的副本
dict_var1 = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
dict_var2 = dict_var1.copy()
print(dict_var2)
fromkeys(…)
Create a new dictionary with keys from iterable and values set to value.
返回拥有指定键和值的字典
dict_var9 = ('key1', 'key2', 'key3')
dict_var10 = 0
dict_var9 = dict.fromkeys(dict_var9, dict_var10)
print(dict_var9)
get(self, key, default=None, /)
Return the value for key if key is in the dictionary, else default.
返回指定键的值
dict_var3 = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
dict_var4 = dict_var3.get("model")
print(dict_var4)
items(…)
D.items() -> a set-like object providing a view on D’s items
返回包含每个键值对的元组的列表
for x, y in dict_var3.items():
print(x, y)
keys(…)
D.keys() -> a set-like object providing a view on D’s keys
返回包含字典键的列表
dict_var5 = dict_var3.keys()
print(dict_var5)
pop(…)
D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
删除拥有指定键的元素
If the key is not found, return the default if given; otherwise,
raise a KeyError.
dict_var3.pop("model")
print(dict_var3)
popitem(self, /)
Remove and return a (key, value) pair as a 2-tuple.
从字典中删除最后一个项目
Pairs are returned in LIFO (last-in, first-out) order.
Raises KeyError if the dict is empty.
dict_var6 = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
dict_var6.popitem()
print(dict_var6)
setdefault(self, key, default=None, /)
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
返回指定键的值。如果该键不存在,则插入具有指定值的键。
dict_var7 = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
dict_var8 = dict_var7.setdefault("model", "Macan")
print(dict_var8)
update(…)
使用指定的键值对字典进行更新
D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k]
D、 更新([E,]**F)->无。从dict/iterable E和F更新D。
如果E存在且有a。keys()方法,然后执行:对于E中的k:D[k]=E[k]
如果E存在且缺少a。keys()方法,然后执行:对于k,E中的v:D[k]=v
在任何一种情况下,后面都是:对于F中的k:D[k]=F[k]
dict_var7.update({"color": "White"})
print(dict_var7)
values(…)
D.values() -> an object providing a view on D’s values
返回字典中所有值的列表
dict_var8 = dict_var7.values()
print(dict_var8)