简体   繁体   中英

Python: Maintaining original order when zipping two lists into a dictionary

I am reading a CSV file and combining rows into dictionaries, with the first row containing the keys and the subsequent rows containing the values. I want my dictionary keys to be in the same order as the original csv file, but the dict(zip)) function seems to order them randomly. I tried OrderedDict and that didn't work.

If there is a better way to produce my dictionaries I'm open to suggestions, but I would really like to know how i can do this while keeping my existing code, just because I am very new to Python (and programming in general) and I would like to be able to understand my own code at this point.

import csv     # imports the csv module

with open("csvfile.csv", "r") as file_var:
    reader = csv.reader(file_var)
    my_list = []
    for row in reader:
        if (len(row)!=0):
            my_list = my_list + [row]

for i in range(1, len(my_list)):
    user = dict(zip(my_list[0], my_list[i]))
    print "----------------------"
    print user['first_name'], user['last_name']
    for key in user:
        print key, user[key]

Dictionaries have an arbitrary order. You should use an OrderedDict instead.

from collections import OrderedDict

user = OrderedDict(zip(my_list[0], my_list[i]))

etc.

I note you say it didn't work, but I see no reason why it wouldn't. In what way did it fail?

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