多语言展示
当前在线:759今日阅读:3今日分享:40

python 容器字典(Dictionaries)简介。

python中使用字典(dictonary)容器来存储 (key, value)对,类似于c++中的unordered_map,是对哈希表的一种具体的实现。下面将对这一容器简单的介绍。
工具/原料
1

python 3.7

2

spyder

方法/步骤
1

字典容器用于存储(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'

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 = {'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

推荐信息