Python Learning Notes Dictionary operation

Source: Internet
Author: User
Tags shallow copy

The dictionary dict is the only built-in mapping type in Python, consisting of key-value pairs, which are unordered. The keys of a dictionary must be immutable objects, such as strings, numbers, tuples, and so on, while lists, dictionaries, and tuples that contain mutable objects cannot be keys. The mutable and immutable meaning here is that the object can be hashed, and the built-in function hash () can be used to test whether the object can be hashed. The value of the dictionary can be any object. The key is denoted by K below, with V to represent the value, the dictionary in the form of D = {k1:v1, k2:v2,..., KN:VN}

Creation of dictionaries

1. Use {} to create

Student = {"name""Jack""Age" " Sex " " male "}

2. Create with keyword Dict

Dict is a python built-in factory function that supports positional parameter *args and keyword parameter **kwargs, where the positional parameter *args is a tuple, so the passed parameters can be converted to a tuple object as long as it is finally possible.

    • Create a dictionary with positional parameters
info = [('name',"Jack"), ('age' , +), ('sex','male')]  = Dict (Info) #方法一: Create a dictionary from a list that is converted to a tuple

Student = Dict ((' Name ', ' Jack '), (' Age ', ' + '), (' Sex ', ' male ')) #方法二: Create directly from tuples
    • Create a dictionary with keyword parameters
Student = Dict (name="Jack", age=14, sex="male")   #关键字参数关键
Studend = Dict () #关键空字典
    • Mixed use positional and keyword parameters to create a dictionary
Student = Dict (('name',"Jack"), ('  Age ()), sex="male")

 3. Use Dict.fromkeys (s, [, values]) to create

Dict.fromkeys (S, [, values]) creates a new dictionary and takes all the elements in the sequence s as keys to the new dictionary, and the values of these keys are value.

m = dict (['K1','K2','k3'], 20)  #m={' K3 ':, ' K2 ': ' K1 ':

  

  Use of dictionaries

The general use of data types, no outside reading, writing, deleting, changing, sorting these kinds, the dictionary is the same.

    • Gets the key of the dictionary
Student = {"name":"Jack"," Age": 14,"Sex":"male"}#方法一: Loopinggets the key of the dictionary forKinchStudent:Printk#方法二: Gets all the keys,call M.keys () to get the sequence of the dictionaryKeys = Student.keys ()#kyes=[' age ', ' name ', ' Sex '
    • Gets the value of the dictionary
# method One: use M[k]  for inch Student:     = Student[k]# method Two: Use M.get (K,[,v]) to get, return m[k], if not found to return v in student:    = M.get (k,"error")# method Three: Get all Values, M.values () Returns the sequence of all values in M = student.values ()      #values = [+, ' Jack ', ' Male ']
    • Gets the key value pair for the dictionary
# method One: Cyclic acquisition  for inch Student:     Pass # method Two: Get all the key-value pairs, M.items () returns (K,v) consisting of the sequence items = Student.items ()  #items = [(' Age ', +), (' Name ', ' Jack '), (' Sex ', ' male ')]
    • Check if key exists
# method One: Use the keyword in if " name " inch Student:     return True # method Two: Use the M.has_keys (k) function (not used in Python3, not recommended) if student.has_keys ("name"):    return True
    • Gets the number of key-value pairs
L = Len (student)  #l = 3
    • Update dictionary
#method One: Update or insert a single value, M[k]=vstudent["name"] ="Jonh"#method Two: Use m.update (b)to add all the objects in B to MStudent.update ([("Grade", 3), ("name","Smith")])#student={' Grade ': 3, ' age ': +, ' name ': ' Smith ', ' sex ': ' Male '}Student.update ({"Grade": 4," Age": 20})#student={' name ': ' Smith ', ' Grade ': 4, ' age ': ' Sex ': ' Male '}#method Three: Use M.setdefault (K,[,v]), if found M[k] return m[k], otherwise m[k] set to V, if not set v default to NoneStudent.setdefault ("Email","[email protected]")#{' name ': ' Smith ', ' Grade ': 4, ' age ': +, ' email ': ' [email protected] ', ' sex ': ' Male '}
    • delete dictionary and value
 #   method one: Delete a single value, Del m[k]  del  student[ name   " "  #   m.pop ( " name  "   #   method Three: M.popitem (), delete a random (k,v) pair, and return it to tuple  item = Student.popitem () #  item = (' Tel ', None)  #   method four: Delete all values,  student.clear () 
    • Copy Dictionary
#call M.copy (), which returns a dictionary of a new shallow copy. Notice the difference between this way and m1=m, m1=m this copy way, dictionary M1 and M#pointing to the same Dictionary object, if you change the key value of the M1, it will also change M. The dictionary obtained with M.copy () is a completely new dictionary.Student = {"name":"Jack"," Age": 14,"Sex":"male"}s1= Student#S1 = {"Name": "Jack", "age": +, "sex": "Male"}S2 = student.copy ()#s2={"name": "Jack", "age": +, "sex": "Male"}s1["name"] ="Bob" #s1=student = {"Name": "Bob", "age": +, "sex": "Male"},student value changeds2["name"] ="Rohn" #s2={"name": "Rohn", "age": +, "sex": "male"},student not changed

   Dictionary Operation function Table

  

Method Name Operation
Dict.clear () Delete all elements in a dictionary
Dict.copy () Returns a copy of the dictionary (shallow copy)
DICT.FROMKEYSC (Seq,val=none) Creates and returns a new dictionary that is the key to the dictionary with the elements in the SEQ, and Val does the initial value for all the keys in the dictionary (the default is None if this value is not provided)
Dict.get (Key,default=none) The key to the dictionary dict, returns the value it corresponds to, and returns the value of default if the key does not exist in the dictionary (note that the default value of the parameter is None)
Dict.has_key (Key) Returns True if the key (key) exists in the dictionary, otherwise false is returned. After the Python2.2 version introduced in and not, this method is almost obsolete, but still provides a working interface.
Dict.items () Returns a list that contains a tuple (key, value) in the dictionary
Dict.keys () Returns a list containing the keys in the dictionary
Dict.values () Returns a list that contains all the values in the dictionary
Dict.iter () Methods Iteritems (), Iterkeys (), and itervalues () are the same as the non-iterative methods they correspond to, but they return an iteration instead of a list.
Dict.pop (key[, default]) Similar to the method get (), if the key key exists in the dictionary, delete and return Dict[key], the Keyerror exception is thrown if the key key does not exist and the value of default is not given.
Dict.setdefault (Key,default=none) Similar to Method set (), if the key key is not present in the dictionary, it is assigned by Dict[key]=default.
Dict.setdefault (Key,default=none) Similar to Method set (), if the key key is not present in the dictionary, it is assigned by Dict[key]=default.

Python Learning Notes Dictionary operation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.