Common functions and usage of dictionary in python

Features of the dictionary:

  key-value structure

  The key must be hashable, must be an immutable data type, and must be unique

  Can store any number of values, can be modified, can not be unique

  disorder

  Find fast

dict_fruit = {'apple':'apple','banana':'banana','cherry':'cherry','avocado':'avocado','watermelon':'watermelon'}

"apple" in dict_fruit >>> True # Determine if it is in the dictionary

for key in dict_fruit: >>> apple,banana,cherry,avocado,watermelon # Traverse the keys in the dictionary (the default traversal is the same as for key in res.keys():)  [find the value of values ​​through this]

for value in res.values(): >>> apple, banana, cherry, avocado, watermelon #traverse the value in the dictionary

for key,value in dict_fruit.items(): >>> apple apple, banana banana, cherry cherry, avocado avocado, watermelon watermelon # Traverse the keys and values ​​in the dictionary [basically not used]

Increase:

dict_fruit["pineapple"] = "pineapple"

delete:

dict_fruit.pop["apple"] #Delete and return the deleted value

dict_fruit.popitem() #Randomly delete the values ​​in the array

change:

dict_fruit["apple"] = "苹果1"

Find:

dict_fruit["apple"] #If the value does not exist, report an error

dict_fruit.get("apple") #get method lookup returns empty if it does not exist

 

dict_fruit.keys() # List all key values

dict_fruit.values() # List all values ​​of value

dict_fruit.items() # put the key and value in the tuple

dict_fruit.update(res) #fill the res dictionary to the value of the key in dict_update

dict_fruit.setdefault(2,3) #Create a new key If there is one in the created key dictionary, return the value of the original key

dict.fromkeys(["a","b","c"],"xhl") #Batch generation of dictionaries of the same value

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324507411&siteId=291194637