简体   繁体   中英

Python iterating/look up dictionary unexpected behavior

I have a problem when I try to look up data in a csv dictionary. A list of dates and times are in one csv and it should look up the data to specific date and time in second csv. I look for an exact match and 22 next records. The problem is that it only fetch for first date and time and rest is not found even though I can see it's there. I feel like this has a very easy solution, but I can't think anything. It must be a problem in my iteration code.

Code:

import csv
csv_eph = open("G:\\db.csv")
csv_reader_eph = csv.reader(csv_eph, delimiter=",")
csv_dict_eph = csv.DictReader (csv_eph)
csv_matches = open("G:\\query.csv")
csv_reader_matches = csv.reader(csv_matches, delimiter=",")
csv_dict_matches = csv.DictReader (csv_matches)

result = []
var = 0
for row in csv_dict_matches:
    datum = row["Date"]
    cas = row["Time"]
    result.append('\n')
    result.append(row)
    for eph in csv_dict_eph:
        if str(eph["datum"]) == str(datum) and str(eph["cas"]) == str(cas):
            var = 23 
        if var > 0:
            result.append(eph)
            var = var - 1

with open("G:\\compiled.txt", "w") as output:
    for item in result:
        output.write(str(item))
        output.write('\n')

SOLUTION, I implemented jasonharper solution and it works flawlesly. many thanks. It was indeed problem with end of dictionary: Now fixed it looks like this and works like intended:

import csv
csv_eph = open("G:\\db.csv")
csv_reader_eph = csv.reader(csv_eph, delimiter=",")
csv_dict_eph = csv.DictReader (csv_eph)
csv_matches = open("G:\\query.csv")
csv_reader_matches = csv.reader(csv_matches, delimiter=",")
csv_dict_matches = csv.DictReader (csv_matches)

#jasonharper
eph_list = []
for eph in csv_dict_eph:
    eph_list.append(eph)


print (eph_list)
result = []
var = 0
for row in csv_dict_matches:
    print (row)
    datum = row["Date"]
    cas = row["Time"]
    result.append('\n')
    result.append(row)
    for eph in eph_list:
        if str(eph["datum"]) == str(datum) and str(eph["cas"]) == str(cas):
            var = 23 
        if var > 0:
            result.append(eph)
            var = var - 1

with open("G:\\compiled.txt", "w") as output:
    for item in result:
        output.write(str(item))
        output.write('\n')

i believe changing:

csv_dict_eph = csv.DictReader (csv_eph)

to:

csv_dict_eph = list(csv.DictReader(csv_eph))

will fix the problem.

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