016 Data Type: Dictionary Type

First, the dictionary (dict)

If there is a demand now I need to save the information, the data types that we learned before, we only list capable of storing information.

user_info = ['xucheng', 'male', '19']

print(user_info[1])  # 'male'
print(user_info[0])  # 'xucheng'
print(user_info[2])  # '19'
male
xucheng
19

While using the list to achieve our purpose, but if you do not know the contents of the list, can not know what I want to express.

So we can not give each element in the list are adding a description of it?

So you can use the new data types - dictionary .

1.1 What is a dictionary type

Dictionary type is a data type, according to the key: value stored-value method, the time taken to go through the key values instead of indexing, has a function key on the descriptive value. Store a variety of types of data and more data when you can use a dictionary.

1.2 Definitions Method

A plurality of values used to access the dictionary, {} in the plurality of elements separated by commas, each element is key: value of the stored-value format, the format in which the data value is arbitrary type, key Because descriptive effect, the key is usually a string type.

user_info = {'name': 'xucheng', 'gender': 'male', 'age': 19}
print(id(user_info))
print(type(user_info))
print(user_info)

Output:

​ 4396183344
​ <class 'dict'>
​ {'name': 'xucheng', 'gender': 'male', 'age': 19}

1.3 Use

Dictionary index value no longer depends on the way, but rather on the key, to obtain the value corresponding to the key value through the [key].

# 字典套列表
user_info = {'name': 'xucheng', 'gender': 'male', 'age': 19,'hobby': ['sing', 'jump', 'rap']}
print(user_info['name'])
print(user_info['hobby'][0])

Output:

​ xucheng
​ sing

# 字典套字典
user_info = {'name': 'xucheng', 'gender': 'male', 'age': 19,'hobby': {'hobby_1':'sing','hobby_2':'jump', 'hobby_3':'rap'}}

print(user_info['name'])
print(user_info['hobby']['hobby_2'])

Output:

​ xucheng
​ jump

Guess you like

Origin www.cnblogs.com/XuChengNotes/p/11271466.html