Python dictionary transformation

Time:2022-1-4

Assume that the dictionary is dics = {0: ‘a’, 1: ‘B’, ‘C’: 3}

1. Take values from the dictionary. Do not want to handle exceptions when the key does not exist

[method] dics get(‘key’, ‘not found’)

[example]

image
[explanation] when the key ‘key’ does not exist, print ‘not found’ (i.e. the information to be handled). When it exists, output the key value.

[other treatment plan I]

if key in dics:

print dics[key] 

else:

print 'not found!!' 

[other treatment plan II]

try:

   print dics[key] 

except KeyError:

   print 'not found' 

example:

image
2. Take values from the dictionary and delete them if found; Do not want to handle exceptions when the key does not exist

[method] dics pop(‘key’, ‘not found’)

[example]

image
[explanation] when the key ‘key’ does not exist, print ‘not found’ (i.e. the information to be processed). When the key exists, output the key value and remove the key.

3. Add an entry to the dictionary. If it does not exist, specify a specific value; If it exists, forget it.

[method] DIC setdefault(key, default)

[example]

image

  1. update

a = {‘a’:1, ‘b’:2}
a.update({‘c’:3})
a
{‘a’: 1, ‘c’: 3, ‘b’: 2}
a.update({‘c’:4})
a
{‘a’: 1, ‘c’: 4, ‘b’: 2}

Recommended Today

SQL server cannot generate fruncm thread

SQL Server was unable to generate the fruncm thread. The database error log is as follows: Copy codeThe code is as follows: 2013-09-26 21:21:50.31 Server      Microsoft SQL Server 2005 – 9.00.1399.06 (Intel X86)Oct 14 2005 00:33:37 Copyright (c) 1988-2005 Microsoft CorporationEnterprise Edition on Windows NT 5.2 (Build 3790: Service Pack 2) 2013-09-26 21:21:50.31 Server      (c) […]