SoFunction
Updated on 2024-10-29

Detailed explanation of dictionary additions, deletions and deletions in Python

Dictionaries in Python

在这里插入图片描述

I. Characteristics of dictionaries

在这里插入图片描述

II. Creating Dictionaries

Creating a dictionary is indicated by curly brackets

dict1={'a':3,'b':4,'c':7}  ## The first way to create
print(dict1)
dict2=dict(a=2,b=3) ## The first way to create
print(dict2)

{'a': 3, 'b': 4, 'c': 7}
{'a': 2, 'b': 3}


III. Querying dictionary data

dict2=dict(a=2,b=3) ## Create a dictionary
print(dict2['a']) ## Look up the value of a in the dictionary and throw an exception if the key does not exist.
print(('a')) ## Make the get method look up the value of a in the dictionary, and return none if the key doesn't exist.

2
2

IV. Key's judgment

dict2=dict(a=2,b=3)
print( 'a' in dict2)
print( 'a' not in dict2)

True
False

V. Deletion of Keys

dict2=dict(a=2,b=3) ## Delete, clear as clear
del dict2['a']
print(dict2)

{'b': 3}

VI. Adding Keys

dict2=dict(a=2,b=3) ##
dict2['c']=4
print( dict2 )

{'a': 2, 'b': 3, 'c': 4}

VII. Modification of Key

dict2=dict(a=2,b=3) ## The first way to create
dict2['c']=4  ##Add c with a value of 4
print( dict2 )
dict2['c']=10 ##Modify the value of c to 10
print( dict2 )

{'a': 2, 'b': 3, 'c': 4} 
{'a': 2, 'b': 3, 'c': 10} ##c has been changed to 10

VIII. Dictionary views

keys()

Get all the keys in the dictionary

test={'Zhang San':56,'Li Si':56}
print(())
print(list(()) ## Convert to list

dict_keys(['Zhang San', 'Li Si'])
['Zhang San', 'Li Si']

values()

Get all values in the dictionary

values=()
print(values)

dict_values([56, 56])
[56, 56]

iterms()

Get all pairs of keys and values in the dictionary.

iterm=()
print(iterm)
print(list(iterm))  ## The list element after conversion is a set of meta-ancestors

dict_items([('Zhang San', 56), ('Li Si', 56)])
[('Zhang San', 56), ('Li Si', 56)]

IX. Iteration of the dictionary

dic1={'a':2,'b':3,'c':4}
for i in dic1:
    print(i)  ## Iterate over the key of the dictionary
    print((i)) ## Printing values using the get function
    print(dic1[i]) ## The second way to traverse values
    

X. Expressions for generating dictionaries

name=['Zhang San','Li Si','Wang Wu']
age=[23,45,37]
d= {name:age for name,age in zip(name,age)} #Note the extra parentheses at the top
print(d)

```
d= {test:age for test,age in zip(name,age)}  ## has nothing to do with the variable name, zip packed values do
print(d) ## Same result
```

{'Zhang San': 23, 'Li Si': 45, 'Wang Wu': 37}
Brackets should be added to the outside.
print(d)

```
d= {test:age for test,age in zip(name,age)}  ## has nothing to do with the variable name, zip packed values do
print(d) ## Same result
```

{'Zhang San': 23, 'Li Si': 45, 'Wang Wu': 37}

summarize

That's all for this post, I hope it was helpful and I hope you'll check back for more from me!