当前位置:网站首页>Use dictionary

Use dictionary

2022-06-24 15:16:00 User 8442333

Dictionary is another variable container model , Similar to the dictionary we use in our life , It can store any type of object , And list 、 The difference between the sets is , Each element of the dictionary consists of a key and a value “ Key value pair ”, Keys and values are separated by colons . The following code shows how to define and use a dictionary .

def main():
	scores = {' Luo Hao ': 95, ' Bai Yuanfang ': 78, ' Judge dee ': 82}
    #  The corresponding value in the dictionary can be obtained through the key 
	print(scores[' Luo Hao '])
	print(scores[' Judge dee '])
    #  Traverse the dictionary ( Traversal is actually the key through the key to get the corresponding value )
	for elem in scores:
		print('%s\t--->\t%d' % (elem, scores[elem]))
    #  Update the elements in the dictionary 
	scores[' Bai Yuanfang '] = 65
	scores[' Wang Lang, Zhuge '] = 71
	scores.update( cold noodles =67,  Fang Qihe =85)
	print(scores)
	if ' Wu zetian ' in scores:
		print(scores[' Wu zetian '])
	print(scores.get(' Wu zetian '))
    # get Method also obtains the corresponding value through the key, but the default value can be set 
	print(scores.get(' Wu zetian ', 60))
    #  Delete elements from Dictionary 
	print(scores.popitem())
	print(scores.popitem())
	print(scores.pop(' Luo Hao ', 100))
    #  Empty dictionary 
	scores.clear()
	print(scores)


if __name__ == '__main__':
	main()
原网站

版权声明
本文为[User 8442333]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/05/20210518112439875d.html