Dictonary
dict.fromkeys(seq[, value])
seq = ('Google', 'Runoob', 'Taobao')
dict = dict.fromkeys(seq)
print "新字典为 : %s" % str(dict)
dict = dict.fromkeys(seq, 10)
print "新字典为 : %s" % str(dict)
https://www.runoob.com/python/att-dictionary-fromkeys.html
Read all items in dictionary
for k,v in info.items():
print('%s is %s'%(k,v))
for k in info2: # 这种方式效率比较高
print(k,info2[k])
https://blog.csdn.net/weixin_33928137/article/details/93172887
如何预防不存在某些‘key’的情形
使用defaultdict
from collections import defaultdict
# Function to return a default
# values for keys that is not
# present
def def_value():
return "Not Present value of the key"
# Defining the dict
d = defaultdict(def_value)
d["a"] = 1
d["b"] = 2
print(d["a"])
print(d["b"])
print(d["c"])
如果已经有了一个dict,可以这么做:
d = defaultdict(def_value, data_dict)
参考:
[1] https://www.geeksforgeeks.org/defaultdict-in-python/
获取某些key
marks = {'Physics':67, 'Maths':87}
print(marks.get('Physics'))
Output: 67
The syntax of get() is:
dict.get(key[, value])
key - key to be searched in the dictionary
value (optional) - Value to be returned if the key is not found. The default value is None.
参考:
[1] https://www.programiz.com/python-programming/methods/dictionary/get