Detailed Explanation of the Usage of dict in python

  • 2021-07-22 09:56:55
  • OfStack

Characteristics of dict

dict is a variable data type in python, denoted by {}, key of dict must be an immutable data type, while value data type can be arbitrary.

Format: {key: value, key: value, key: value}
Note: If the key-value pair is a string, single quotation marks are used, and the last key-value pair has no comma

Advantages of dict

①: The query speed is fast, and it can be searched in 2 points

② key can not be repeated

Note:

Immutable data types: tuples, bool, int, str can be hash set

Variable data types: dict, list

Method of dict

1. Methods of adding: dict has two methods of adding

(1) If there is no key-value pair, add it; if there is, overwrite the value


dict1={'name':'jinxin','age':18,'male':' Male '}
print(dict1)
dict1['high']=185
print(dict1) # {'name': 'jinxin', 'age': 18, 'male': ' Male ', 'high': 185}
dict1['age']=16
print(dict1) # {'name': 'jinxin', 'age': 16, 'male': ' Male ', 'high': 185}

(2) If there is a key-value pair, do not make any changes. If there is no key-value pair, add it


dict1.setdefault("weight")
print(dict1) #{'name': 'jinxin', 'age': 16, 'male': ' Male ', 'high': 185, 'weight': None}
dict1.setdefault('weight','65kg')
print(dict1) #{'name': 'jinxin', 'age': 16, 'male': ' Male ', 'high': 185, 'weight': None}
dict1.setdefault('address',' Beijing ')
print(dict1) #{'name': 'jinxin', 'age': 16, 'male': ' Male ', 'high': 185, 'weight': None, 'address': ' Beijing '}

2. Deletion method of dict

(1) Use pop () to delete. If there is a key, delete it. If there is no key, it will report an error. If you don't want to report an error, you can add information after deletion


delDict={'name': 'jinxin', 'age': 16, 'male': ' Male ', 'high': 185, 'weight': None, 'address': ' Beijing '}
# delDict.pop('age') #dict The delete operation of has a return value 
print(delDict.pop('age')) # 16
print(delDict) #{'name': 'jinxin', 'male': ' Male ', 'high': 185, 'weight': None, 'address': ' Beijing '}
print(delDict.pop(' Occupation ',' This key is not available ')) # This key is not available 

(2), use popitem () delete, random delete, return is a tuple, the key value of deletion stored in the tuple, recommend using pop () method to delete


print(delDict.popitem()) # ('address', ' Beijing ')

Random deletion, the return value is the deleted key-value pair


print(delDict) #{'name': 'jinxin', 'male': ' Male ', 'high': 185, 'weight': None}

(3) Use del () to delete. del () can delete the whole dictionary or a key of the dictionary. If the deleted key does not exist, an error will be reported


del delDict['name']
print(delDict) #{'male': ' Male ', 'high': 185, 'weight': None}
# Use del Empty the list 
del delDict
print(delDict) #delDict Has been deleted , Report an error 

(4), you can also use clear () to empty the list

3. Modification of dict


# Direct modification 
updateDict={'name':'jinxin','age':18,'male':' Male '}
updateDict['name']='Jordan'
print(updateDict['name']) #Jordan

# Call update() Modify 
dictDemo={'name':"Jordan",'age':18}
dictDemo1={'address':' Haidian, Beijing ','age':22}
dictDemo.update(dictDemo1)
print(dictDemo)

4. Dictionary query

(1) Query dictionary keys: Call keys () method

Query dictionary values: Call the values () method


#  Dictionary search 
dict1={'name':'jinxin','age':18,'male':' Male '}
print(dict1.keys()) #dict_keys(['name', 'age', 'male'])
print(dict1.values()) #dict_values(['jinxin', 18, ' Male '])
print(dict1.items())# dict_items([('name', 'jinxin'), ('age', 18), ('male', ' Male ')])

# Print dict1 Key of 
for i in dict1.keys():
  print(i ) # name age value

# Print dict Value of 
for v in dict1.values():
  print(v) #jinxin 18  Male 

# Print dictionary key values: 

dict1={'name':'jinxin','age':18,'male':' Male '}

for i in dict1.items():
  print(i) # ('name', 'jinxin') ('age', 18) ('male', ' Male ')
  
for k,v in dict1.items():
  print(k,v) # name jinxin age 18  male  Male 

(2) get () method of dictionary: get () method can be used to query whether a key exists. If this key does not exist, None will be returned, but information can be added in get () method to avoid None


dict1={'name':'jinxin','age':18,'male':' Male '}
print(dict1.get('name')) #jinxin
print(dict1.get('address')) # None
print(dict1.get('address',' This key is not available ')) # This key is not available 

Related articles: