A brief discussion on Python dictionary (Dictionary) operations

This article mainly introduces the detailed operation method of Python dictionary (Dictionary). Friends who need it can refer to it.

Python dictionary is another mutable container model and can store any type of object, such as strings, numbers, tuples and other container models.

1. Create a dictionary

A dictionary consists of pairs of keys and corresponding values. Dictionaries are also called associative arrays or hash tables. The basic syntax is as follows:

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

You can also create a dictionary like this

dict1 = { 'abc': 456 }
dict2 = { 'abc': 123, 98.6: 37 }

Notice:

Each key and value are separated by a colon (:), each pair is separated by a comma, and the whole is placed in curly braces ({}).
Keys must be unique, but values ​​do not.
Values ​​can be of any data type, but must be immutable, such as strings, numbers, or tuples.

2. Access the values ​​in the dictionary

Put the corresponding keys in familiar square brackets, as in the following example:

1

2

3

4

5

6

7

dict = { 'Name': 'Zara', 'Age': 7, 'Class': 'First'};

print "dict['Name']: ", dict['Name'];

print "dict['Age']: ", dict['Age'];

#以上实例输出结果:

#dict['Name']: Zara

#dict['Age']: 7

If you access data using keys that are not in the dictionary, the following error will be output:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

print "dict['Alice']: ", dict['Alice'];

The output of the above example is:

#KeyError: 'Alice'

3. Modify the dictionary

The method of adding new content to the dictionary is to add new key/value pairs, modify or delete existing key/value pairs, as shown in the following example:

1

2

3

4

5

6

7

8

dict = { 'Name': 'Zara', 'Age': 7, 'Class': 'First'};

dict['Age'] = 8; # update existing entry

dict['School'] = "DPS School"; # Add new entry

  

print "dict['Age']: ", dict['Age'];

print "dict['School']: ", dict['School'];

#Output results of the above example:

#dict['Age']: 8
#dict['School']: DPS School

4. Delete dictionary elements

You can delete a single element or clear the dictionary. Clearing only requires one operation.
Use the del command to delete a dictionary, as shown in the following example:

1

2

3

4

5

6

7

8

9

10

dict = { 'Name': 'Zara', 'Age': 7, 'Class': 'First'};

del dict['Name']; # 删除键是'Name'的条目

dict.clear();  # 清空词典所有条目

del dict # 删除词典

print "dict['Age']: ", dict['Age'];

print "dict['School']: ", dict['School'];

#但这会引发一个异常,因为用del后字典不再存在:

dict['Age']:

5. Characteristics of dictionary keys

Dictionary values ​​can take any Python object without restrictions, either standard objects or user-defined, but keys cannot.
Two important points to remember:

1) The same key is not allowed to appear twice. If the same key is assigned twice during creation, the latter value will be remembered, as in the following example:

1

2

3

4

5

dict = { 'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};

print "dict['Name']: ", dict['Name'];

#以上实例输出结果:

#dict['Name']: Manni

2) The key must be immutable, so it can be used as a number, string or tuple, so a list will not work, as shown in the following example:

1

2

3

4

5

dict = {['Name']: 'Zara', 'Age': 7};

print "dict['Name']: ", dict['Name'];

#以上实例输出结果:

#TypeError: list objects are unhashable

6. Dictionary built-in functions & methods

The Python dictionary contains the following built-in functions:

cmp(dict1, dict2) #Compare two dictionary elements.
len(dict) #Calculate the number of dictionary elements, that is, the total number of keys.
str(dict) #Output the printable string representation of the dictionary.
type(variable) #Return the input variable type. If the variable is a dictionary, return the dictionary type.

Python dictionaries contain the following built-in methods:

radiansdict.clear() #删除字典内所有元素
radiansdict.copy() #返回一个字典的浅复制
radiansdict.fromkeys() #创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
radiansdict.get(key, default=None) #返回指定键的值,如果值不在字典中返回default值
radiansdict.has_key(key) #如果键在字典dict里返回true,否则返回false
radiansdict.items() #以列表返回可遍历的(键, 值) 元组数组
radiansdict.keys() #以列表返回一个字典所有的键
radiansdict.setdefault(key, default=None) #和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为default
radiansdict.update(dict2) #把字典dict2的键/值对更新到dict里
radiansdict.values() #以列表返回字典中的所有值

转自:微点阅读   https://www.weidianyuedu.com

Guess you like

Origin blog.csdn.net/weixin_45707610/article/details/131768018