最近字典用的较多,小总结一下:
1.创建新字典,只引入key。比如列表或者元组值 转字典key等情况使用
seq = ['Google', 'Runoob', 'Taobao']
thisdict = dict.fromkeys(seq)
print(thisdict)
#结果:{'Google': None, 'Taobao': None, 'Runoob': None}
2.一个键对应多个值
setdefault + append: 多个值存为列表形式
dict={} #初始化字典
dict.setdefault("num",[]).append("A")
dict.setdefault("num",[]).append("a")
print(dict)
#结果:{'num': ['A','a']}
setdefault + update:嵌套字典
dict={} #初始化字典
dict.setdefault("num",{}).update({"A":"T"}) #格式化字典
dict.setdefault("num",{}).update({"C":"G"})
print(dict)
#{'num': {'A': 'T', 'C': 'G'}}
3.遍历字典,获取键值
dict = {"a":1, "b":2, "c":3, "d":1, "e":2}
print(dict.keys()) #获取所有的key 值
#结果:dict_keys(['a', 'b', 'c', 'd', 'e'])
print(dict.values()) #获取所有的value 值
#结果:dict_values([1, 2, 3, 1, 2])
#遍历字典
for k,v in dict.items():
print(k,v)
#结果a 1
# b 2
# c 3
# d 1
# e 2
for key in dict:
print(key + '对应的值为:'+str(dict[key]))
#结果:a对应的值为:1
b对应的值为:2
c对应的值为:3
d对应的值为:1
e对应的值为:2
4.字典包含字典写法,用文本测试。
{'sent0': {'Thomas': 1, 'Jefferson': 1, 'began': 1, 'building': 1, 'Monticello': 1, 'at': 1, 'the': 1, 'age': 1, 'of': 1, '26.': 1}, 'sent1': {'Construction': 1, 'was': 1, 'done': 1, 'mostly': 1, 'by': 1, 'local': 1, 'masons': 1, 'and': 1, 'carpenters.': 1}}
sentence = """Thomas Jefferson began building Monticello at the age of 26.\n"""
sentence += """Construction was done mostly by local masons and carpenters.\n"""
corpus = {}
for i, sent in enumerate(sentence.split('\n')): #i是索引, sent是句子
corpus['sent{}'.format(i)] = dict((tok, 1) for tok in sent.split())
结果:
5.其他
其他方法可参考链接:
https://www.jb51.net/article/163967.htm