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

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/sinat_34611224/article/details/84957815

Lesson 15

Introduction

In computer science, there is a data structure called an associative array (associative array), it will have done the mapping (map). In python, this data structure is defined as a dictionary (dictionary). When your data needs to be key-value (key: input -map-> value: output) when formatting, you need a dictionary.

Create a New Dictionary

Suppose we want to build a new social networking site called FriendFace. We want to gather information related to each new user registration, including user name, profile, language, registration time and location. Then such data python how to deal with it?

# 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"...}

We now create a dictionary of (mappings) of a key contains five. If you treat it as a map, it will correspond to the five inputs (key), five output (output). Note that the values ​​of the key and data types may be all the data tuple type or the like.

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

This means that we can use the dictionary dict construction, pay attention to this section are using python3. Next, we use dict post information to construct another FriendFace of:

# 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'}
# 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'}

From this experiment, we can see two way information is added to the dictionary: the first approach, the key is no need for quotation marks; the second approach, the use of parentheses and quotation marks are defined.

Accessing Data in Dictionaries

# To see the message from the first post, use the key name "message"
print(post["message"])
D5 E4 F4 C5 G3
 # 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'

We will find, location is not defined in the key post2, so it will go wrong. So, how to avoid this happen? [Tips: single or double quotes can be. ] We offer two ways:

 # 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.
# 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.

Another way to get the data dictionary, we use dir (), help () to find it:

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']

We can find the "get" this method, with help () to see what does it do:

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 () can try to get the value of the corresponding key, if not in the dictionary should be key-value pairs, you can specify a default value. Here, we use this method to add value to the location of post2.

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

Other Operations

User information back to the beginning of the post, a common task is to enumerate the key information in the dictionary:

print(post)
{'user_id': 209, 'message': 'D5 E4 F4 C5 G3', 'language': 'English', 'datetime': '20181212', 'location': (44.590533, -104.715566)}
# 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)

Here we use keys () can get all the keys in the dictionary. Note python2 in this chapter is different because the print method python3 more powerful.

# 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 () can get a dictionary of all the pairs. Of course, the operation of the dictionary, there are many, such as pop (), popitem () can remove a key-value pair in the dictionary; clear () can be directly emptied dictionary. Try multi-related, you will find more.

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

Guess you like

Origin blog.csdn.net/sinat_34611224/article/details/84957815