All operation methods of Python dict dictionary

1. Introduction

Dictionaries are another mutable container model and can store objects of any type.
Each key-value key=>value pair of the dictionary is separated by a colon:, and each pair is separated by a comma (,). The entire dictionary is included in curly braces {}, and the format is as follows:

d = {
    
    key1 : value1, key2 : value2, key3 : value3 }

Note: As dict is a keyword and built-in function of Python, it is not recommended to name the variable as dict.

dict

The key must be unique, but the value does not have to, the value can take any data type, but the key must be immutable, such as string, number.

The "key" in the dictionary can be any immutable data in Python, such as integers, real numbers, complex numbers, strings, tuples, etc., but you cannot use lists, sets, and dictionaries as the "keys" of dictionaries, because these objects are variable changing. In addition, the "key" in the dictionary does not allow repetition, but the value can be repeated.

Note: The key of a dictionary in Python must be a specific number, or an immutable sequence. List is a mutable sequence that provides insertion, deletion, and modification operations, while tuple is an immutable sequence, and there are no append(), extend(), and insert() functions that can modify the sequence .

2. The creation of the dictionary

1. Manual creation

Manually create dictionaries directly using the equals sign:

a_dict={
    
    'DXY':"19950819" , 'HJL':"19960424"}
print(a_dict)  #{'HJL': '19960424', 'DXY': '19950819'}
print(type(a_dict))  #<class 'dict'>  为字典类型

2. Use the built-in function dict() to create

dictionary=dict( [["a",1],["b",2],["c",3]] )
print(dictionary)   #{'b': 2, 'a': 1, 'c': 3}
print( type(dictionary ))  #<class 'dict'>

Use "'key'='value'" as an argument to dict() to create a dictionary:

a_dict=dict(name='DYX' ,  age=24)  #键=值对
print(a_dict)  #{'age': 24, 'name': 'DYX'}

3. Use the dict.fromkeys() method to create

Use the dict.fromkeys() method to create a dictionary with an empty "value" given a sequence of "keys":

a_dict=dict.fromkeys( ['name','age','sex'] )
print(a_dict)  #{'sex': None, 'name': None, 'age': None}
#“键”是给出的序列中的元素,“值”为空。

3. Reading of dictionary elements

1. Read Value by subscript

Similar to lists, you can use subscripts to access the elements in the dictionary, but the difference is that the subscripts of the dictionary are the "keys" of the dictionary, while the subscripts must be integer values ​​when accessing lists and tuples. When accessing the dictionary "value" by subscript, an exception is thrown if the specified key does not exist.

a_dict = {
    
    'name':'DYX', 'sex':'male', 'age':24}
print(a_dict['name'])  #DYX
#print(a_dict['tel'])  KeyError: 'tel' 不存在抛出异常

2. dict.get() reads Value

Use the get() method of the dictionary object to obtain the "value" corresponding to the specified "key", and return the specified value when the specified "key" does not exist. If not specified, it will return None by default. Compared with the above method, this method is more secure.
That is: the subscript index method will throw an exception if the specified key does not exist, and the get() method will return the specified value, or None.

a_dict = {
    
    'name':'DYX', 'sex':'male', 'age':24}
print(a_dict.get('ranking'))   #None  指定的键ranking不存在返回None
print(a_dict.get('ranking','No entry'))  #No entry  指定的键不存在,返回指定的内容No entry

3. The keys() method returns "keys"

a_dict = {
    
    'name':'DYX', 'sex':'male', 'age':24}
print(a_dict.keys())    #输出字典的键 dict_keys(['name', 'age', 'sex'])
print(type(a_dict.keys())) #查看一下类型 <class 'dict_keys'>
print(list(a_dict.keys()))  #['age', 'name', 'sex']
 
#可以用循环的方式输出
for key in a_dict.keys():
    print(key, end = " ")  #name sex age

4. The values() method returns "values"

a_dict = {
    
    'name':'DYX', 'sex':'male', 'age':24}
print(a_dict.values())    #输出字典的值 dict_values(['male', 'DYX', 24])
print(type(a_dict.values())) #查看一下类型 <class 'dict_values'>
print(list(a_dict.values()))  #['male', 'DYX', 24]
#这里也可以体现字典的无序性。
 
for key in a_dict.values():
    print(key, end = " ")  #male DYX 24 

5. The items() method returns a "key-value" pair

a_dict = {
    
    'name':'DYX', 'sex':'male', 'age':24}
print(a_dict.items())  #dict_items([('age', 24), ('name', 'DYX'), ('sex', 'male')])
print(type(a_dict.items()))  #<class 'dict_items'>
 
#通常用遍历来做
for item in a_dict.items():
    print(item, end = " ")  #('sex', 'male') ('name', 'DYX') ('age', 24)
#查看一下item的类型
print("\n",type(item))  # <class 'tuple'> 元组类型

The output can also be iterated like this:

a_dict = {
    
    'name':'DYX', 'sex':'male', 'age':24}
for key,values in a_dict.items():
    print(key,values) #单纯遍历输出两个值,所以不是元组形式
#age 24
#sex male
#name DYX

If you traverse the dictionary directly, you can only traverse the "key":

a_dict = {
    
    'name':'DYX', 'sex':'male', 'age':24}
for item in a_dict:    #默认是遍历“键”
    print(item, end = " ")  #name age sex

4. Addition and modification of dictionary elements

1. Add and modify by subscript

When "key" is used as a subscript, if the key exists, modify the value corresponding to the key, and if the key does not exist, add a new "key-value" pair.

a_dict = {
    
    'name':'DYX', 'sex':'male', 'age':24}
a_dict['name']="DDD"
print(a_dict)  #{'age': 24, 'sex': 'male', 'name': 'DDD'}
#进行了修改
 
a_dict['ranking']=15   #不存在该键,所以添加新的键值对。
print(a_dict)   #{'ranking': 15, 'age': 24, 'name': 'DDD', 'sex': 'male'}

2. The update() method adds key-value pairs

The update() method of the dictionary object can add another dictionary to the current dictionary. If the same "key" exists in the two dictionaries, the current dictionary will be updated based on the "value" in the other dictionary .

a_dict = {
    
     'ranking': [98, 97] ,  'age': 24 ,  'name': 'DYX' ,  'sex': 'male' }
#字典中的“值”可以是列表、数字、字符串元组等等,是很宽泛的
#字典中的“键”要注意不能使用列表、集合、字典作为字典的“键”
print(a_dict.items())
#dict_items([('sex', 'male'), ('age', 24), ('name', 'DYX'), ('ranking', [98, 97])])
a_dict.update( {
    
    'a':'a','b':'b'} )  
print(a_dict)  #查看添加后的字典
#{'sex': 'male', 'age': 24, 'ranking': [98, 97], 'name': 'DYX', 'a': 'a', 'b': 'b'}

3. delete

3.1 del command

The del command deletes the element corresponding to the specified "key" in the dictionary. Or delete the dictionary itself:

a_dict = {
    
    'name':'DYX', 'sex':'male', 'age':24}
del a_dict["name"]
print(a_dict)  #{'age': 24, 'sex': 'male'}
del a_dict
print(a_dict)  #NameError: name 'a_dict' is not defined  报错
3.2 clear() method

The clear() method of the dictionary deletes all elements in the dictionary, but the dictionary still exists, just an empty dictionary:

a_dict = {
    
    'name':'DYX', 'sex':'male', 'age':24}
a_dict.clear()
print(a_dict)  #{}
#注意和del 的不同,del是删除整个字典,clear()方法是删除字典里面的元素。
3.3 pop() method

The pop() method removes and returns the element at the specified "key":

a_dict = {
    
    'name':'DYX', 'sex':'male', 'age':24}
temp = a_dict.pop("name")
print(temp) #DYX
print(a_dict)  #{'age': 24, 'sex': 'male'}
3.4 popitem () method

Return and delete the last key and value pair in the dictionary . Delete and return the last inserted key-value pair (key, value format), according to the LIFO (Last In First Out) sequence rule, that is, the last key-value pair. If the dictionary is already empty and this method is called, a KeyError exception will be reported.
Example:

#!/usr/bin/python3

site= {
    
    'name': '菜鸟教程', 'alexa': 10000, 'url': 'www.runoob.com'}

# ('url': 'www.runoob.com') 最后插入会被删除
result = site.popitem()

print('返回值 = ', result)
print('site = ', site)

# 插入新元素
site['nickname'] = 'Runoob'
print('site = ', site)

# 现在 ('nickname', 'Runoob') 是最后插入的元素
result = site.popitem()

print('返回值 = ', result)
print('site = ', site)
返回值 =  ('url', 'www.runoob.com')
site =  {
    
    'name': '菜鸟教程', 'alexa': 10000}
site =  {
    
    'name': '菜鸟教程', 'alexa': 10000, 'nickname': 'Runoob'}
返回值 =  ('nickname', 'Runoob')
site =  {
    
    'name': '菜鸟教程', 'alexa': 10000}

5. Determine whether the key is in the dictionary

in to judge whether the key is in the dictionary:

a_dict = {
    
    'name':'DYX', 'sex':'male', 'age':24}
print("name" in a_dict) #True
print("ranking" in a_dict) #False

6. Ordered dictionary

Python's built-in dictionary is unordered. If you need a dictionary that can remember the insertion order of elements, you can use collections.OrderedDict:

x=dict()   #创建一个无序字典
x['a']=3   #有就修改元素的“值”,无就在字典中更新这个“键-值对”
x['b']=5
x['c']=8
print(x)   #输出无序{'b': 5, 'c': 8, 'a': 3}
print(x.items())  #dict_items( [ ('c', 8), ('a', 3), ('b', 5) ] )
print(dict(x.items()))  # {'b': 5, 'a': 3, 'c': 8}

Note: After python 3.8, the original dict dictionary is supported as an ordered dictionary

import collections
x=collections.OrderedDict()  #创建一个有序字典
x['a']=3   #有就修改元素的“值”,无就在字典中更新这个“键-值对”
x['b']=5
x['c']=8
print(x)    #OrderedDict( [ ('a', 3), ('b', 5), ('c', 8) ] )
print( dict(x) )   #又变为无序字典{'b': 5, 'a': 3, 'c': 8}

7. Copy and shallow copy of dictionary

Use the copy() method to realize the "shallow copy" of the dictionary, and modify the dictionary generated by the shallow copy without affecting the original dictionary.

1. Shallow copy

a_dict = {
    
    'name':'DYX', 'sex':'male', 'age':24}
b_dict = a_dict.copy()
print(b_dict)  #{'age': 24, 'name': 'DYX', 'sex': 'male'}
b_dict["name"] = "DDD"
print(b_dict)  #{'sex': 'male', 'name': 'DDD', 'age': 24}
print(a_dict)  #{'sex': 'male', 'name': 'DYX', 'age': 24}
#修改b_dict不影响a_dict

2. Copy

a_dict = {
    
    'name':'DYX', 'sex':'male', 'age':24}
c_dict = a_dict
c_dict["name"] = "DDD"
print(c_dict)  #{'sex': 'male', 'name': 'DDD', 'age': 24}
print(a_dict) #{'sex': 'male', 'name': 'DDD', 'age': 24}
#修改c_dict等同修改a_dict

Eight. Dictionary sorting

1. Sort according to "Key":

test_dict = {
    
    "DDD":15, "CMJ":43, "HLZ":66, "HXH":39}
#依据五选排名(不懂的忽略我这句注释)
sorted_key = sorted(test_dict)
print(sorted_key )  #['CMJ', 'DDD', 'HLZ', 'HXH']
#print(type(sorted_key))  #<class 'list'>
for k in sorted_key:
    print(k, test_dict[k],end = " ")  #CMJ 43 DDD 15 HLZ 66 HXH 39

2. Sort according to "Value"

test_dict = {
    
    "DDD":15, "CMJ":43, "HLZ":66, "HXH":39}
sorted_value = sorted(test_dict, key=test_dict.__getitem__)
print(sorted_value)  #['DDD', 'HXH', 'CMJ', 'HLZ']
for k in sorted_value:
    print(k, test_dict[k],end = " ")  #DDD 15 HXH 39 CMJ 43 HLZ 66

3. Sort according to items()

3.1 Sort by key
test_dict = {
    
    "DDD":15, "CMJ":43, "HLZ":66, "HXH":39}
res = sorted(test_dict.items())
print(res)  #[('CMJ', 43), ('DDD', 15), ('HLZ', 66), ('HXH', 39)]
#等同于
res = sorted(test_dict.items(),key=lambda d:d[0])
print(res) #[('CMJ', 43), ('DDD', 15), ('HLZ', 66), ('HXH', 39)]
3.2 Sorting by value
res = sorted(test_dict.items(),key=lambda d:d[1])
print(res)  #[('DDD', 15), ('HXH', 39), ('CMJ', 43), ('HLZ', 66)]
3.3 Sort from big to small: reverse=True

The above are sorted from small to large, if you want to sort from large to small, add reverse=True to sorted():

res = sorted(test_dict.items(),key=lambda d:d[1],reverse = True)
print(res)  #[('HLZ', 66), ('CMJ', 43), ('HXH', 39), ('DDD', 15)]

4. With operator.itemgeter()

import operator
test_dict = {
    
    "DDD":15, "CMJ":43, "HLZ":66, "HXH":39}
##按照item中的第一个字符进行排序,即按照key排序
sort_by_key = sorted(test_dict.items(),key = operator.itemgetter(0))
print(sort_by_key)  #[('CMJ', 43), ('DDD', 15), ('HLZ', 66), ('HXH', 39)]
 
##按照item中的第一个字符进行排序,即按照value排序
sort_by_value = sorted(test_dict.items(),key = operator.itemgetter(1))
print(sort_by_value) #[('DDD', 15), ('HXH', 39), ('CMJ', 43), ('HLZ', 66)]
 
#同样可以逆序
sort_by_value = sorted(test_dict.items(),key = operator.itemgetter(1),reverse = True)
print(sort_by_value) #[('HLZ', 66), ('CMJ', 43), ('HXH', 39), ('DDD', 15)]

9. Dictionary built-in functions & methods

dict

dict

dict

10. Reference Links

  1. Python dictionary (Dictionary) operation full solution [create, read, modify, add, delete, ordered dictionary, shallow copy, sort]
  2. Python3 dictionary: https://www.runoob.com/python3/python3-dictionary.html

Guess you like

Origin blog.csdn.net/flyingluohaipeng/article/details/129312124