Learn python with socratica [My notes] - part 13- Dictionary in Python

Lesson 15

Introduction

在计算机科学中,有一种数据结构叫关联数组(associative array),也就做映射(map)。在python中,这个数据结构被定义为字典(dictionary)。当你的数据需要以key-value(key:input -map-> value:output)的格式处理时,就需要字典。

Create a New Dictionary

假设我们要建立一个新的社交网站,叫做FriendFace。我们要为每一个注册的新用户收集相关的信息,包括用户名、简介、语言、注册时间和地理位置。那么这样的数据该怎么用python处理呢?

1
2
3
4
5
6
7
8
9
# FriendFace Post
# User_id = 209
# message = "D5 E4 F4 C5 G3"
# language = "English"
# datetime = "20181212"
# location = (44.590533,-104.715566)

# we can use a single object to store all of this date
post = {"user_id":209, "message":"D5 E4 F4 C5 G3", "language":"English", "datetime":"20181212", "location":(44.590533,-104.715566)} # format:{"key":"value"...}

我们现在创建了一个包含五个键值对(映射关系)的字典。如果你把它当作映射图,那么也就对应五个输入(key),五个输出(output)。需要注意的是,键和值的数据类型可以是所有的数据类型或者tuple等。

1
2
type(post) 
# if you use the type function, you will find post belongs to "dict"
dict

这就意味着,我们可以用dict构造字典,注意本节都使用的是python3。接下来,我们使用dict去构造另一个FriendFace的post信息:

1
2
3
4
5
# This time, we use dict.
post2 = dict(message="SS Cotopaxi", language="English")

# We can see this made a dictionary
print(post2)
{'message': 'SS Cotopaxi', 'language': 'English'}
1
2
3
4
# We add additional pieces of data by using brackets.
post2["user_id"] = 209
post2["datetime"] = "20181213"
print(post2)
{'message': 'SS Cotopaxi', 'language': 'English', 'user_id': 209, 'datetime': '20181213'}

从这个实验,我们可以看到两种给字典加信息的方式:第一种方式,对键值不需要引号;第二种方式,使用括号和引号来定义。

Accessing Data in Dictionaries

1
2
# To see the message from the first post, use the key name "message"
print(post["message"])
D5 E4 F4 C5 G3
1
2
 # Try to get a info. which is not included by post2
print(post2['location'])
---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

<ipython-input-6-840c4f5feede> in <module>()
----> 1 print(post2['location'])

KeyError: 'location'

我们会发现,location这个键在post2中没有被定义,这样去找就会出错。那么,怎么去避免这种情况发生呢?【Tips:单引号或者双引号都可以。】我们提供两种方式:

1
2
3
4
5
 # First, to check if the key is in the dictionary
if "location" in post2:
print(post2['location'])
else:
print("The post does not contain a location value.")
The post does not contain a location value.
1
2
3
4
5
# Second, try and retrieve the value, but handle the possibility of a KeyError
try:
print(post2['location'])
except KeyError:
print("The post does not contain a location value.")
The post does not contain a location value.

还有一种方式去获取字典中的数据,我们用dir(),help()去寻找吧:

1
dir(post2)
['__class__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'clear',
 'copy',
 'fromkeys',
 'get',
 'items',
 'keys',
 'pop',
 'popitem',
 'setdefault',
 'update',
 'values']

我们可以找到“get”这个方法,用help()看看它有什么作用:

1
help(post2.get)
Help on built-in function get:

get(...) method of builtins.dict instance
    D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.

get() 可以试着去获取对应键的值,如果字典中没有值对应该键,你可以指定一个默认值。下面,我们用该方法去给post2加上location的值。

1
2
loc = post2.get('location', None)
print(loc)
None

Other Operations

回到一开始的post用户信息,一个常见的任务就是把字典中的键值信息列举出来:

1
print(post)
{'user_id': 209, 'message': 'D5 E4 F4 C5 G3', 'language': 'English', 'datetime': '20181212', 'location': (44.590533, -104.715566)}
1
2
3
4
# A common way: loop over all the keys
for key in post.keys():
value = post[key]
print(key, "=", value)
user_id = 209
message = D5 E4 F4 C5 G3
language = English
datetime = 20181212
location = (44.590533, -104.715566)

这里我们使用keys()可以得到字典中所有的键。注意python2中的这部分会有所不同,这是因为python3中print方法更强大了。

1
2
3
# Another way
for key, value in post.items():
print(key, "=", value)
user_id = 209
message = D5 E4 F4 C5 G3
language = English
datetime = 20181212
location = (44.590533, -104.715566)

items()可以获取字典中所有的键值对。当然,对字典的操作还有很多,比如pop(),popitem()就可以去掉字典中的某个键值对;clear()可以直接清空字典。多试试相关的方法,你会有更多发现。

Youtube source:
https://www.youtube.com/watch?v=bY6m6_IIN94&list=PLi01XoE8jYohWFPpC17Z-wWhPOSuh8Er-