Dictionary (to be supplemented)

Usage setdefault function
dict.setdefault (key, default = None)
function:
if the key does not exist in the dictionary, it will add the value of the key and default is set to the default value of the key, if the key exists in the dictionary, the the key value corresponding to the read original, default value does not overwrite the already existing key value

update

  • d1.update(d2)
    • The contents of the dictionary is added to the d2 d1 dictionaries
d1 = {'name':'xiaoge','age':15}
d2 = {'face':'cool'}
d1.update(d2)
print('value:%s'%d1)
d2.update(d1)
print(d2)
#value:{'name': 'xiaoge', 'age': 15, 'face': 'cool'}
 {'face': 'cool', 'name': 'xiaoge', 'age': 15}

get setdefault

  • Similarly Python dictionary get () method and setDefault () method returns the value of the specified key, if the key is not in the dictionary, returns a specific value, the default is None
    get () and setDefault () difference: setdefault () Returns the key if not dictionary, will add key (updated dictionary), and get () does not add keys.
a = {'int':0}
b = a.get('int')
d = a.get('age',18)
print(b)		#0
print(d)		#18
c = a.get('age')
print(c)		#None
e = a.setdefault('int')
print(e)		#0
print(a)		#{'int': 0}
f = a.setdefault('age',10)
print(f)		#10
print(a)		#{'int': 0, 'age': 10}

pop

  • Delete key returns the key-value pairs and
  • pop () method syntax:D.pop(key[,default])
  • parameter
    • key: To delete a key / value pair corresponding to the key
    • default: an optional parameter given when the key is not in the dictionary must be set, whether the person will be given (no default value), then returns the default value
a = {'name':'xiaoge','age':18,'face':'handsome'}
b = a.pop('name')
c = a.pop('like','yang')	#这样是对的
d = a.pop('age',15) #如果没有age键,则返回设置的默认值15,如果有,返回age对应的值
print(a,b,c,d)
#{'age': 18, 'face': 'handsome'} xiaoge yang 18
#下面的d是错的,因为没有键like,而且没给like设置默认值
d = a.pop('like')	
#KeyError: 'like'

Guess you like

Origin blog.csdn.net/xiaogeldx/article/details/90509987