Python dictionary related knowledge

1. Classification of data types

Divide by mutable and immutable

Mutable (hashable)

listdictset

Immutable (unhashable)

strboolinttuple

2. First introduction to dictionary

  • Dictionaries are container data:dict
  • Format:以{}括起来,以键值对形式存储的容器型数据类型。
dict1={
    
    '老师':
       {
    
    'name':'吕小树','age':25,'sex':'男'}'18秋法学本科班':
       ['王小二','李铁柱','李黑碳']
      }
  • key:唯一的,必须是不可变的数据类型:int、str(常用),bool、tuple(几乎不用)
  • value:可重复的,可以是任意数据类型,对象。
  • The differences between dictionaries in various versions of Python:
字典3.5版本之前(包括3.5)是无序的。
字典3.6x会按照初次建立字典的顺序排列,但学术上不认为是有序的。
字典3.7x以后都是有序的。
  • Advantages of dictionaries:查询速度非常快,存储关联性的数据
  • Disadvantages of dictionaries:以空间换时间。

3. Use of dictionary (add, delete, modify and look up)

How to create a dictionary

# 方式一:
dict1 = dict((('one', 1), ('two', 2),('three', 3)))
print(dict1)
>>>{
    
    'one': 1, 'two': 2, 'three': 3}
# 方式二:
ict1 = dict(one=1, two=2, three=3)
print(dict1)
>>>{
    
    'one': 1, 'two': 2, 'three': 3}
# 方式三(官方写法):
dict1 = dict({
    
    'one': 1, 'two': 2, 'three': 3})
print(dict1)
>>>{
    
    'one': 1, 'two': 2, 'three': 3}
# 方式四:
dict1 = {
    
    'one': 1, 'two': 2, 'three': 3}

increase

# 直接增加:有则改之,无则增加。
dict1['name'] = '吕小树'
dict1['one'] = 'one'		# 已经存在则修改原键对应的值
# 直接以键名增加,有则改之,无则增加。
# dict.setdefault()方法:有则不变,无则增加。
dict1.setdefault('sex','男')
dict1.setdefault('name','吕布')
>>>{
    
    'one': 1, 'two': 2, 'three': 3, 'name': '吕小树', 'sex': '男'}

delete

  • dict.pop()方法 (***):删除键值对。删除指定键,返回该键对应的值。
# 典型应用:在pop方法后面加一个参数,如果这个字典里没有要删除的这个键,则返回后面参数的内容,程序不会报错。
dict1 = {
    
    'one': 1, 'two': 2, 'three': 3}
print(dict1.pop('age','没有此键'))
>>>{
    
    'one': 1, 'two': 2, 'three': 3}
  • dict.clear()方法:清空该字典,并非删除这个字典。
  • dict.del()方法:删除指定键值对,但没有返回值,如果字典中无该键,程序报错。
dict1 = {
    
    'one': 1, 'two': 2, 'three': 3}
del dict1['one']
>>>{
    
    'two': 2, 'three': 3}

change

  • dict['键名'] = 值
  • dict.updata()方法

check

  • Query by key name: If there is no key name to query, the program will report an error.
dict1 = {
    
    'one': 1, 'two': 2, 'three': 3, 'name': '吕小树', 'sex': '男'}
print(dict1['name'])
>>>吕小树
  • dict.get() method★★★: If there is no key name to be queried, 'None' will be returned, or the specified content will be returned.
dict1 = {
    
    'one': 1, 'two': 2, 'three': 3, 'name': '吕小树', 'sex': '男'}
print(dict1.get('age'))
>>>None
print(dict1.get('age','没有此键'))
>>>没有此键
  • dict.keys() method: The return value is a list, mostly used with for loops.
dict1 = {
    
    'one': 1, 'two': 2, 'three': 3, 'name': '吕小树', 'sex': '男'}
print(dict1.keys())
dict.values()方法:返回值是一个列表,多用于跟for循环使用。

dict1 = {
    
    'one': 1, 'two': 2, 'three': 3, 'name': '吕小树', 'sex': '男'}
for value in dict1.values():
    print(value)
  • dict.items() method: Returns each key-value pair (tuple), mostly used for for loops combined with traversing each key-value pair of the entire dictionary.
dict1 = {
    
    'one': 1, 'two': 2, 'three': 3, 'name': '吕小树', 'sex': '男'}
for key,value in dict1.items():		# 将每个元组拆包赋值给对应的两个变量。
    print(key,value)
>>>one 1
two 2
three 3
name 吕小树
sex 男

4. Nesting of dictionaries

dict1 = {
    
    
    'name': '李小伟',
    'age': 26,
    'wife': [{
    
    'name': '小章', 'age': 22},],
    'children': {
    
    'girl': '小苹果', 'boy': '小圈'}
}
# 获取李小伟的名字
print(dict1.get('name'))
# 获取这个字典:{'name': '小章', 'age': 22}
print(dict1['wife'][0])
# 获取李小伟妻子的名字
print(dict1['wife'][0]['name'])
# 获取李小伟男孩的名字
print(dict1['children']['boy'])
>>>
李小伟
{
    
    'name': '小章', 'age': 22}
小章
小圈

5. Comprehensive application: string to dictionary

  • The string "k: 1|k1:2|k2:3 |k3 :4" is processed into a dictionary {'k':1,'k1':2…}
  msg = 'k: 1|k1:2|k2:3 |k3 :4| K4: 58'
  dict1 = {
    
    }						# 创建一个空字典
  list1 = msg.split('|')				# 将字符串以'|'符号分割
  for i in list1:
      key, value = i.split(':')			        # 将列表中每个元素以':'符号分割成两部分,分别赋值
      dict1.setdefault(key.strip(), int(value.strip()))	# 构造字典
  print(dict1)
  >>>{
    
    'k': 1, 'k1': 2, 'k2': 3, 'k3': 4, 'K4': 58}

Picture sharing

Insert image description here

Guess you like

Origin blog.csdn.net/Jo_Francis/article/details/125334891