1、字典容器用于存储钱砀渝测(key,value)对,是对哈希表的实现,访问时间复杂度为o(1).简单用法如下:d = {泌驾台佐39;cat': 'cute', 'dog': 'furry'} # Create a new dictionary with some dataprint(d['cat']) # Get an entry from a dictionary; prints "cute"print('cat' in d) # Check if a dictionary has a given key; prints "True"d['fish'] = 'wet' # Set an entry in a dictionaryprint(d['fish']) # Prints "wet"# print(d['monkey']) # KeyError: 'monkey' not a key of dprint(d.get('monkey', 'N/A')) # Get an element with a default; prints "N/A"print(d.get('fish', 'N/A')) # Get an element with a default; prints "wet"del d['fish'] # Remove an element from a dictionaryprint(d.get('fish', 'N/A')) # "fish" is no longer a key; prints "N/A"
2、上述代码运行结果:cuteTruewetN/AwetN/A
3、循环:遍历字典中的key非常简单。实现如下:d = {'person': 2, 'cat': 4, 'spider': 8}for animal in d: legs = d[animal] print('A %s has %d legs' % (animal, legs))# Prints "A person has 2 legs", "A cat has 4 legs", "A spider has 8 legs"
4、结果如下:A person has 2 legsA cat has 4 legsA spider has 8 legs
5、如果你想同时获取字典的key和相应的value的话,可以使用items方法。举个例子:d = {泌驾台佐39;person': 2, 'cat': 4, 'spider': 8}for animal, legs in d.items(): print('A %s has %d legs' % (animal, legs))# Prints "A person has 2 legs", "A cat has 4 legs", "A spider has 8 legs"
6、结果如下:A person has 2 legsA cat has 4 legsA spider has 8 legs
7、可以简单的通过列表构建字典。举个例子:nums = [0, 1, 2, 3, 4]even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}print(even_num_to_square) # Prints "{0: 0, 2: 4, 4: 16}"结果为:{0: 0, 2: 4, 4: 16}