Python Dictionary (dict) and list (list) and array (nbarray) details

Posted by charlie2869 on Sun, 23 Feb 2020 12:32:42 +0100

 

Catalog

 

I. dictionary

Declaring dictionary

Empty dictionary declaration method

Common declaration method (key: value = 1:1)

Add a new key value pair to the dictionary

Dictionary format

Traversal of dictionaries

Common loop traversal and output the value of the corresponding key

Traverse the value of each key horizontally, and get a maximum value (one dimension) for each completed row

Traverse the value of each key longitudinally, and get a maximum value (one dimension) for each completed column

Dictionary operation: sorting and updating

Sort by key

Ranking by value

Sorting values and keys in tuples

More concise sorting by referencing the itemgetter package

Update with updata function

Two, list

Declaration list

Empty list declaration method

Common list declaration method

Add new values to the list

The difference between append function and extend function

List format:

Traversal of list

Traverse directly by range

Traversal by element

List operation: cut, splice

List cut

List stitching

 

Three, array

Declare array mode

Normal array declaration method

Declare all 0 array zeros

Declare all 1 array ones

Declare random number array

Generate evenly distributed array

Format of array:

Array traversal is the same as list traversal

Traverse directly by range

Traversal by element

Array operation: cut, splice

The array is first converted to a list, then cut and spliced in the form of a list, and then converted back to an array.

shape and reshape of array

I. dictionary

  • Declaring dictionary

  1. Empty dictionary declaration method

    dict = {}
  2. Common declaration method (key: value = 1:1)

    #One-dimensional
    dict = {key1 : value1, key2 : value2 }
    
    #Multidimensional
    dict_2d = {'a': {'a': 1, 'b': 3}, 'b': {'a': 6}}
  3. Add a new key value pair to the dictionary

    #One-dimensional
    dict.setdefault(key,value)
    
    #Two-dimensional
    def addtodict2(thedict, key_a, key_b, val): 
        if key_a in thedict:
            thedict[key_a].update({key_b: val})
        else:
            thedict.update({key_a:{key_b: val}})
    
    #Multidimensional
    def addtodict3(thedict,key_a,key_b,key_c,val):
        if key_a in thedict:
            if key_b in thedict[key_a]:
                thedict[key_a][key_b].update({key_c:val})
            else:
                thedict[key_a].update({key_b:{key_c:val}})
        else:
            thedict.update({key_a:{key_b:{key_c:val}}})

    (if you want a value to correspond to multiple values, you can set the value to a list or array)

 

  • Dictionary format:

  1. The key must be unique, but the value is not.

  2. Value can take any data type, but the key must be immutable

  • Traversal of dictionaries

  1. Common loop traversal and output the value of the corresponding key

    #One-dimensional
    
    #General loop traversal
    for key, value in dict.items():
        print(key+':'+str(value))
    
    
    #Output the value corresponding to the keyword
    print(dict[key])
    
    
    #Multidimensional
    for key1 in thedict:
        for key2 in thedict[key1]:
            for key3 in thedict[key1][key2]:
                print (key3+":"+str(thedict[key1][key2][key3]))

     

  2. Traverse the value of each key horizontally, and get a maximum value (one dimension) for each completed row

    maxvaluelist=[]
    maxkeylist=[]
    valuelength=0
    for k,v in data.item():Get once data Of value Length
        valuelength = len(v)
        break
    
    for i in range(0,valuelength):#The start and end of traversal is the length of 0-valuelength
        maxvalue=0
        maxkey=''
        for k,v in data.item():#Traverse every key
            if v[i]>maxvalue :
                maxvalue = v[i]
                maxkey = k
            else continue
        maxvaluelist.append(maxvalue)
        maxkeylist.append(maxkey)
             
  3. Traverse the value of each key longitudinally, and get a maximum value (one dimension) for each completed column

 

 

maxvaluelist={}


    for k,v in data.item():#Traverse every key
        maxvalue = 0
        for item in v:
        if item>maxvalue :
            maxvalue = item
        else: continue
        maxvaluelist.setdefault(k,maxvalue)
    
  • Dictionary operation: sorting and updating

  1. Sort by key

    #Forward sort
    dict1={'a':2,'e':3,'f':8,'d':4}
    dict2 = sorted(dict1)
    print(dict2)
    
    #output
    
    >>['a', 'd', 'e', 'f']
    
    
    #Reverse sorting
    dict1={'a':2,'e':3,'f':8,'d':4}
    dict2 = sorted(dict1,reverse=True)
    print(dict2)
    
    #output
    >>['f', 'e', 'd', 'a']

     

  2. Ranking by value

    dict1={'a':2,'e':3,'f':8,'d':4}
    list1= sorted(dict1.values())
    print(list1) 
    
    #output
    >>[2, 3, 4, 8]
    
    #Set reverse=True to reverse sort
  3. Sorting values and keys in tuples

    #Use dict1.items() to get the tuple containing key and value
    
    #Since the iteration object is a tuple, the return value is naturally a list of tuples
    
    #Here, the sorting rules are defined: X refers to tuple, x[1] is value, x[0] is key)
    
    dict1={'a':2,'e':3,'f':8,'d':4}
    list1= sorted(dict1.items(),key=lambda x:x[1])
    print(list1)
    
    #output
    >>[('a', 2), ('e', 3), ('d', 4), ('f', 8)]
    
    
    #Similarly, key sorting includes:
    
    dict1={'a':2,'e':3,'f':8,'d':4}
    list1= sorted(dict1.items(),key=lambda x:x[0])
    print(list1)
    
    #output
    >>[('a', 2), ('d', 4), ('e', 3), ('f', 8)]
  4. More concise sorting by referencing the itemgetter package

    from operator import itemgetter
    d = {"a":8,"b":4,"c":12}
    print(sorted(d.items(),key=itemgetter(0),reverse=True))
    print(sorted(d.items(),key=itemgetter(1),reverse=True))
    
    #itemgetter(0), get key
    
    #itemgetter(1), get value
    
    #output
    >>[('c', 12), ('b', 4), ('a', 8)]
    >>[('c', 12), ('a', 8), ('b', 4)]
  5. Update with updata function

    # Pass in a dictionary and change the original value
    
    d = {'one':1,'two':2}
    d.update({'one':3,'two':4})
    print(d)
    
    >>{'one': 3, 'two': 4}
    
    
    # Pass in a dictionary and add a new key value pair
    
    d = {'one':1,'two':2}
    d.update({'three':3,'four':4})
    #Or we can use its equivalent
    #d.update(three=3,four=4) 
    #d.update([('three',3),('four',4)])
    
    print(d)
    
    {'four': 4, 'one': 1, 'three': 3, 'two': 2}
    

     

Two, list

  • Declaration list

  1. Empty list declaration method

    list = []
  2. Common list declaration method

    list1 = ['Beijing', 'Shenzhen', 1998, 2020];
    list2 = [1, 2, 3, 4, 5 ];
    list3 = ["a", "b", "c", "d"];
  3. Add new values to the list

    list.append(value)
  4. The difference between append function and extend function

    #Using append
    a = [1, 2, 3]
    b = [4, 5, 6]
    a.append(b)
    print(a)
    #output
    >>[1, 2, 3, [4, 5, 6]]
    
    
    #Using extend
    a = [1, 2, 3]
    b = [4, 5, 6]
    a.extend(b)
    print(a)
    //output
    >>[1, 2, 3, 4, 5, 6]

     

  • List format:

 

Data items of the list do not need to have the same type

  • Traversal of list

  1. Traverse directly by range

    #One-dimensional
    
    for i in range(0,len(list)):
        print(list(i))
    
    #Two-dimensional
    for i in range(0,len(list)):
        for j in range(0,len(list[i]):
            print(list[i][j])
    
  2. Traversal by element

    #One-dimensional
    
    for item in list:
        print(item)
    
    #Two-dimensional
    for x in list:
        for y in x:
            print(y)
    
  • List operation: cut, splice

  1. List cut

    list=['123','abc',0,True]
    x=list[1:]
    y=list[:3]
    z=list[2:3]
    print(x)
    print(y)
    
    
    #output
    >>['abc', 0, True]
    >>['123', 'abc', 0]
    >>[0]
    
    
    #Add step length
    #Format: variable [head subscript: tail subscript: step size]
    list=['123','abc',0,True,"12345"]
    x=list[1:4:2]
    print(x)
    
    #output
    >>['abc', True]

     

  2. List stitching

    list1 = [1,2,3]
    list2 = [4,5,6]
    
    #Use + splicing
    newlist = list1+list2
    print(newList)
    
    #output
    >> [1,2,3,4,5,6]
    #-----------------------------
    #Slicing and stitching
    newList=list1
    newList[len(list1),len(list2)] = list2
    
    #output
    >> [1,2,3,4,5,6]
    #-----------------------------
    #Use extend as mentioned above

     

 

Three, array

  • Declare array mode

  1. Normal array declaration method

    #One-dimensional
    np.array([2,3,4])
    
    #Multidimensional
    np.array([2,3,4],[5,6,7])
    
  2. Declare zero array

     np.zeros( (3,4) )
    
    #output
    >>>array([[ 0.,  0.,  0.,  0.],
             [ 0.,  0.,  0.,  0.],
             [ 0.,  0.,  0.,  0.]])
  3. Declare all 1 array ones

    np.ones( (2,3,4), dtype=np.int16 )                # dtype can also be specified
    >>array([[[ 1, 1, 1, 1],
            [ 1, 1, 1, 1],
            [ 1, 1, 1, 1]],
            [[ 1, 1, 1, 1],
            [ 1, 1, 1, 1],
            [ 1, 1, 1, 1]]], dtype=int16)
  4. Declare random number array

    np.empty( (2,3) )                               # uninitialized, output may vary
    
    >>array([[  3.73603959e-262,   6.02658058e-154,   6.55490914e-260],
            [  5.30498948e-313,   3.14673309e-307,   1.00000000e+000]])
  5. To generate a evenly distributed array:

Range (min, Max, step) (left closed right open)

linspace (min, Max, number of elements)

np.arange( 10, 30, 5 )

#output
>>array([10, 15, 20, 25])

np.arange( 0, 2, 0.3 )                 # it accepts float arguments

#output
>>array([ 0. ,  0.3,  0.6,  0.9,  1.2,  1.5,  1.8])
 
np.linspace( 0, 2, 9 )                 # 9 numbers from 0 to 2

#output
>>array([ 0.  ,  0.25,  0.5 ,  0.75,  1.  ,  1.25,  1.5 ,  1.75,  2.  ])

 

  • Format of array:

ndarray.ndim: dimensions of an array
ndarray.shape: the size of each dimension of the array
ndarray.size: the number of all elements in the array
ndarray.dtype: the type of elements in the array (numpy.int32, numpy.int16, and numpy.float64, etc.)
ndarray.itemsize: several bytes per element

  • The traversal of an array is the same as that of a list

  1. Traverse directly by range

    #One-dimensional
    
    for i in range(0,len(list)):
        print(list(i))
    
    #Two-dimensional
    for i in range(0,len(list)):
        for j in range(0,len(list[i]):
            print(list[i][j])
    
  2. Traversal by element

    #One-dimensional
    
    for item in list:
        print(item)
    
    #Two-dimensional
    for x in list:
        for y in x:
            print(y)
    
  • Array operation: cut, splice

  1. The array is first converted to a list, then cut and spliced in the form of a list, and then converted back to an array.

    #List & matrix to array
    
    array = np.array(list)
    
    array = np.array(matrix)
    
    # List & array transformation matrix
    
    matrix = np.mat(list)
    
    matrix = np.mat(array)
    
    
    # Array & matrix to list 
    
    list = array.tolist()     
    
    list = matrix.tolist()
    
      
    
    
    
  2. shape and reshape of array

import numpy as np
#Use of shape
a = np.array([1,2,3,4,5,6,7,8])  #One-dimensional array
print(a.shape[0])  #The value is 8 because there are 8 data
print(a.shape[1])  #IndexError: tuple index out of range

a = np.array([[1,2,3,4],[5,6,7,8]])  #Two-dimensional array
print(a.shape[0])  #The value is 2, the outermost matrix has 2 elements, 2 elements or matrix.
print(a.shape[1])  #The value is 4, and the inner matrix has four elements.
print(a.shape[2])  #IndexError: tuple index out of range


#Usage of reshape
a = np.array([1,2,3,4,5,6,7,8])  #One-dimensional array

a_2d = a.reshape(2,4)
#output
>>[[1,2,3,4],
   [5,6,7,8]]

a_3d = a.reshape(2,2,2)
#output
>>[[[1,2],[3,4]],[[5,6],[7,8]]]

 

The above is the basic knowledge accumulated by all bloggers about dictionaries, arrays and lists. Hope to help you!

39 original articles published, 43 praised, 70000 visitors+
Private letter follow

Topics: Lambda