简体   繁体   中英

for loop to get the elements in key value pair

Im trying to read data from a csv file and want to store it in a key value pair.

code im trying is as follows:

csv_data = []
with open('/Users/tejas/textTocsv/pair.csv') as paircsv:
    reader = csv.DictReader(paircsv, delimiter = ',' )
    for row in reader:
        #im stucked over here

pair.csv data

id   ppid
1    22rt3
12   3456r4
23   w232w

I want the data to be in key value pair so that i can use it further in the program. Thank you in advance.

You are on the right track, but as @Heike pointed out you are better off with a csv.reader over a csv.DictReader given the structure of your data. Here is an example of how you can start with csv file and end up with a dictionary for use later in your program.

Example:

from io import StringIO
import csv

# Simplified the example using StringIO instead of file I/O.
# Note: replaced spaces with commas as delimeters
paircsv = StringIO("""id,ppid
1,22rt3
12,3456r4
23,w232w
""")

# Commenting this out for StringIO example
# with open('/Users/tejas/textTocsv/pair.csv') as paircsv:

reader = csv.reader(paircsv, delimiter = ',' )

# Construct a dictionary from the key, value pairs in the CSV file
csv_data = {
    key: value
    for key, value in reader
}

print(my_dict)

Output:

{'id': 'ppid', '1': '22rt3', '12': '3456r4', '23': 'w232w'}

A simple example for storing in a dictionary

import csv

csv_data={}

with open("/Users/tejas/textTocsv/pair.csv") as paircsv:
    reader =csv.reader(paircsv)
    for key,value in reader:
        csv_data[key]=value

print(csv_data)

Outpt

{'id': 'ppid', '1': '22rt3', '12': '3456r4', '23': 'w232w'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM