SoFunction
Updated on 2024-11-21

Python write csv data to list and dictionary type variable script method

Python write csv data to list and dictionary type variable script method

Updated June 15, 2018 16:13:20 by Badass Is Me
Today I will share with you a Python write csv data to list and dictionary type variable script method, has a good reference value, I hope to help you. Together follow the editor over to see it

As shown below:

#coding=utf8
import csv 
import logging
(level=,
        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
        datefmt='%a, %d %b %Y %H:%M:%S',
        filename='',
        filemode='w')
'''
The main function of this module, based on an existing csv file, is to
Through the readDataToDicl function, the corresponding part of the csv.
into a dictionary, each dictionary as a json data
'''
class GenExceptData(object):
  def __init__(self):
    try:
      # Stores the data read from the csv
      =[]
      # Open csv file, set read permissions
      csvHand=open("","r")
      # Create a handle to read a csv file.
      readcsv=(csvHand)
      #Read csv data into mdbuffer
      for row in readcsv:
          (row) 
      # Dress the data as a dictionary of type
      #()
      #Save the file
    except Exception,e:
      ("Read Excel error:"+e) 
    finally:
      #Close csv file
      ()
 
  def readDataToList(self):
    try:
      # Get the number of elements in mdbuffer
      rowNumber=len()
      # Set the current line number
      currentrow=1
      # Setting property values of json data
      propertyJson={}
      #propertyJsonList=[]
      #count=0
      # Read the elements of the list
      dataList=[] 
      try: 
        for row in range(1,rowNumber):
          # Create a temporary variable to access the attribute key values for a single loop
          temp={}
          
          # Get an element of the list
          item=[row]
          # Get the current element, which represents each of the
          # Position where the event started
          currentItem=[currentrow]
          # Get serviceId and decode it.
          serviceId= currentItem[2].decode("gbk")
          # Get the property and decode it, store the decoded value into propertyName
          propertyName=item[3].decode("gbk")
          # Get the property value and decode it, store the decoded value into propertyValue
          propertyValue=item[4].decode("gbk")
          try:
            # Determine if buried events are equal to serviceId
            if item[0]==currentItem[0] and item[2]==currentItem[2]:
              # Put the serviceId method dictionary propertyJson
              propertyJson["serviceId"]=serviceId 
              # Putting attribute/value pairs into temp dictionary
              temp[propertyName]=propertyValue
              # Call the dictionary's update function to put the key-value pairs in temp
              # Add to the propertyJson dictionary
              (temp)
              # Use continue to loop through the if statement module if the if condition is true.
              continue 
            else:
              # Set the line number to the current line
              currentrow=row 
              # Decode the current property into propertyName
              propertyName=currentItem[3].decode("gbk")
              # Decode the current property value into propertyName
              propertyValue=currentItem[4].decode("gbk")
              # Put the serviceId method dictionary propertyJson
              propertyJson["serviceId"]=serviceId  
              #Put property/value pairs into propertyJson dictionary
              propertyJson[propertyName]=propertyValue
              #(propertyJson) 
              (propertyJson)
              '''
              Here goes:
              The difference between () and propertyJson={}:
              () is deleting the value of the dictionary without creating a reference, which changes the value of the dictionary itself;
              propertyJson={} is creating a new reference, the value in the dictionary is not found to change;
              If you want the (propertyJson) statement to execute successfully and add values for each loop, you need to use the propertyJson={} statement.
              you need to use the propertyJson={} method;
              If you use (), you will only add the last propertyJson value stored in the
              '''
              propertyJson={}
          except Exception,e:
            ("Get Property Json Error:"+e) 
            print "Get Property Json Error:",e
      except Exception,e:
        ("Get Date Error:"+e) 
        print "Get Date Error:",e
      return dataList   
    except Exception,e:
      ("Reading Data TO Dic Error:"+e) 
      print "Reading Data TO Dic Error:",e
    
  def getAllServiceId(self):
    try:
      dataList=()
      serList=[item["serviceId"] for item in dataList if item["serviceId"] ] 
      serList=list(set(serList))
      return serList
    except Exception,e:
      ("Create ServiceId List Error:"+e)
      print "Create ServiceId List Error:"+e
                    
  def oupPutData(self):
    try:
      dataList=()
      for item in dataList:     
          print "{"  
          for key,val in (): 
            print key,":",val
          print "}"
          print "#"*50
    except Exception,e:
      ("OutPut Data Error:"+e)
      print "OutPut Data Error:"+e
  
   
  def createDataDic(self):
    try:
      dataDic={}
      
      dataList=()
      count=0
      for item in dataList:
        if item["serviceId"]==u"pageview":
          count+=1
      print count
          
      serviceIdList=()
      if len(serviceIdList)>0 and len(dataList)>0:
        for serviceId in serviceIdList:
          sameServiceidJosnList=[]
          for item in dataList:          
            itemServiceId=item["serviceId"]
            if itemServiceId:
              if serviceId==itemServiceId: 
                (item)                               
            else:
              print "ServiceId is null"
          dataDic[serviceId]=sameServiceidJosnList 
          
      else:
        print "seriviceIdList or dataList is null"
      return dataDic
      ''' 
      for key,val in ():
        print key,len(val)
        print "*"*50
        for item in val:
          print "{"
          for ke,va in ():
            print ke,":",va
          print "}"
        print "-"*50
      '''
    except Exception,e:
      print "Create Data Dictionary Error:",e 
    
def test():
  gen =GenExceptData()
  ()
  
if __name__=="__main__":
  test()

Above this Python write csv data to list and dictionary type variable script method is all I have shared with you, I hope to give you a reference, and I hope you support me more.

  • Python
  • csv
  • list
  • dictionaries

Related articles

  • Python simple implementation of the web page content capture function example

    This article introduces the Python simple implementation of the web page content capture function, combined with examples of the form of analysis of the Python web page based on the urllib module request, content reading and other related skills, you can refer to below
    2018-06-06
  • Example code for converting a list of numbers to a string of numbers in python

    Previously studied, numbers and strings can be stored in the variable, the following article introduces a list of numbers in python into a digital string of relevant information, the text of the example code through the introduction of very detailed, the need for friends can refer to the next!
    2023-02-02
  • Python logging module handlers usage in detail

    This article introduces the Python logging module handlers usage details, the text of the sample code through the introduction of the very detailed, for everyone to learn or work with certain reference learning value, you can refer to the following friends
    2020-08-08
  • Examples of Python exception handling operations in detail

    This article introduces the Python exception handling operations, combined with examples of the form analyzes the Python common types of exception handling, related operational techniques and considerations, need friends can refer to the following
    2018-08-08
  • Python thread lock (thread) learning example

    python thread provides low-level, primitive threads and a simple lock, the following provides a python thread thread lock (thread) to learn the example, we refer to the use of
    2013-12-12
  • A brief introduction to the python thread pool simple application

    This article introduces a brief python thread pool simple application, thread pool at the start of the system that creates a large number of idle threads, the program as long as a function submitted to the thread pool, the thread pool will start a free thread to execute it, the need for friends can refer to the following
    2023-04-04
  • 3 Python SQLAlchemy Database Operation Functions Explained

    Python SQLAlchemy is a powerful and versatile Python SQL toolkit and object-relational mapping (ORM) system , provides a set of well-known enterprise-class persistence model , this article for you to organize it must understand the 3 database operation functions , I hope to help you!
    2023-09-09
  • Implementing Image Correction in opencv

    This article is mainly for you to introduce in detail the realization of opencv image correction, the sample code in the text is very detailed, with certain reference value, interested partners can refer to it!
    2022-08-08
  • Python scripts to handle timestamps, time calculations, etc. shared

    This article mainly for you to organize a summary of five practical Python small, you can achieve timestamp processing and time calculation. The sample code in the article explains the details, interested partners can learn a little
    2022-07-07
  • Example code for adding, deleting, and checking python lists

    The following editorial will share a python list of add, delete, change and check example code, has a good reference value, I hope to help you. Together follow the editor over to see it
    2018-01-01

Latest Comments