Dictionary of python entry

1. The basic features of the dictionary:

key-value structure

The key is unique and must be an immutable data type

value can not be unique

disorder

Find fast

 

2. Create a dictionary:

info={“gaohui”:"IT",21,"PYTHON","hong":"stu",22,"java",2:3}

 

3. Add content to the dictionary:

info["aaa"]=any form of number

 

4. Delete the content in the dictionary:

Method 1: info.pop("gaohui")#Delete the key of gaohui

Method 2: info.popitem()#Delete randomly

Method 3: del info["gaohui"]#Delete the key of gaohui

 

5. Modify the content in the dictionary:

info["aaa"]=any form of number This aaa is a key value in the dictionary

 

6. Check the contents of the dictionary

"gaohui" in info #Check if there is a key of gaohui in the dictionary

info.get("gaohui") Get the content in the key of gaohui

info["gaohui"]

The difference between the two methods:

#When using info.get(), the obtained key is empty, and the output value is none #When
using info[], the obtained value is empty, and an error will be reported at this time

info.keys()#outputs the keys of the dictionary
info.values()#outputs the content in the keys of the dictionary

 

7.info.update

info={"gaohui":[21,"man","IT"],"hongyan":[23,"woman","student"],"aaa":[22,"bbb","ccc"] }
info2={"aa":2,2:3,"hongyan":[22,"woman","student"]}
info.update(info2)#When the keys in info2 and info are the same, the key in info2 The content will overwrite the content in info, and the duplicated key printed at this time is the value in info2

 

8.info.setdefault

info2={"aa":2,2:3,"hongyan":[22,"woman","student"]}
info2.setdefault(2,"aaa")#If your dictionary has the key 2, Then the output is the value corresponding to key2 in the dictionary. If there is no key 2, then the output is aaa

 

9.info.fromkeys

info2={"aa":2,2:3,"hongyan":[22,"woman","student"]}
# print(info2.fromkeys(["a","b","c"], "gaohui"))#Make a dictionary with the same value in batches

 

10. Dictionary loop

for k in info2:
print(k,info2[k])#dictionary loop, print out key and corresponding value

 

Guess you like

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