python 3.7
spyder
字典容器用于存储(key,value)对,是对哈希表的实现,访问时间复杂度为o(1).简单用法如下:d = {'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'
上述代码运行结果:cuteTruewetN/AwetN/A
循环:遍历字典中的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'
结果如下:A person has 2 legsA cat has 4 legsA spider has 8 legs
如果你想同时获取字典的key和相应的value的话,可以使用items方法。举个例子:d = {'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'
结果如下:A person has 2 legsA cat has 4 legsA spider has 8 legs