Dictionary addition, deletion and modification

check

dict1 = {'name': 'Eagle Eye Mihawk ",' age ': 19,' hobby ': [' Pirate ',' Sword
Art ']} print (dict1 [' hobby ']) # [' 海贼',' Sword Skill '] # If you don't have this key, you will get an error

Check get

print (dict1.get ('666')) # None Without this key returns None
print (dict1.get ('666', 'Prompt for not having this key')) # Specify two parameters without error. Return the information of the second parameter: prompt that there is no such key

查 keys values items

dic = {'name': 'Haha', 'dream': 'to be number', 'age': 19}
print (dic.values ​​()) # Note that the returned list is not pure. dict_values ​​(['哈哈', 'to be number', 19])
l = list (dic.keys ()) # key can be converted into a list
print (l) # ['name', 'dream', 'age']

key

for k in dic:
print(k)
'''
name
dream
age
'''

value

for value in dic.values():
print(value)
'''
哈哈
to be number
19
'''

item

print(dic.items()) # dict_items([('name', '哈哈'), ('dream', 'to be number'), ('age', 19)])

Single element returns tuple

for i in dic.items():
print(i)
'''
('name', '哈哈')
('dream', 'to be number')
('age', 19)
'''

Unpacking with tuples returns key, and value

for k, v in dic.items():
print(k + ":", v)
'''
name: 哈哈
dream: to be number
age: 19
'''

Two elements interchange

a = 18
b = 12
a, b = b, a
print(a, b)

Guess you like

Origin www.cnblogs.com/jnsn/p/12735088.html