Python-based dictionary dict

#Characteristics of the dictionary, the key-value pair appears {key:value}, the definition of the dictionary{}
#The key of the dictionary cannot be repeated. If the key is repeated, the last element is added to the dictionary by default, and multiple elements are separated by commas.
#Dictionaries are unordered
#Define a dictionary: example
dic={'a':1,'b':2}

# Common methods of dictionary
The #fromkeys parameter is an iterable type, which turns each iterative object into the key of the dictionary, and the value defaults to None. The example can be modified
#Note Note that fromkeys returns a new dictionary and does not modify the current dictionary
dic.fromkeys ('adsfakj')

#How to get the elements in the dictionary? Use get() with two parameters, the first is the key, the second is the prompt message returned when there is no return value, the default is None
dic.get('a','a's value is empty')

#items returns all elements, the return value type is dict_item After getting the return value, it will generally be converted into a list example
list(dic.items())
#The form after conversion to list is that the list contains the tuple, and the tuple is the K and V of the dictionary
'''
[('a', 1), ('b', 2)]
'''
# keys returns all the keys in the dictionary and then the list is converted to a list of lists
list(dic.keys())
'''
['a','b']
'''

#values ​​and keys are used in the same way, but one takes k and the other v

# pop() parameter is k if there is no value, an error will be reported and can be customized

#popitem Pop a key-value pair at will

#setdefault adds an element without changing the value of the element if it already exists


#How to modify the dictionary?
#1, modify the value by key
dic ['a'] = 3

#2, update modifies elements, you can change many elements at a time, modify them if they exist, and add them if they don’t exist
dic.update({'a';10,'b':20,c:'100'})
#
#QQ:8131432
 

Guess you like

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