开发者

Python CSV search for specific values after reading into dictionary

开发者 https://www.devze.com 2023-02-08 14:51 出处:网络
I need a little help reading specific values into a dictionary u开发者_JAVA技巧sing Python. I have a csv file with User numbers. So user 1,2,3... each user is within a specific department 1,2,3... and

I need a little help reading specific values into a dictionary u开发者_JAVA技巧sing Python. I have a csv file with User numbers. So user 1,2,3... each user is within a specific department 1,2,3... and each department is in a specific building 1,2,3... So I need to know how can I list all the users in department one in building 1 then department 2 in building 1 so on. I have been trying and have read everything into a massive dictionary using csv.ReadDict, but this would work if I could search through which entries I read into each dictionary of dictionaries. Any ideas for how to sort through this file? The CSV has over 150,000 entries for users. Each row is a new user and it lists 3 attributes, user_name, departmentnumber, department building. There are a 100 departments and 100 buildings and 150,000 users. Any ideas on a short script to sort them all out? Thanks for your help in advance


A brute-force approach would look like

import csv
csvFile = csv.reader(open('myfile.csv'))
data = list(csvFile)
data.sort(key=lambda x: (x[2], x[1], x[0]))

It could then be extended to

import csv
import collections

csvFile = csv.reader(open('myfile.csv'))
data = collections.defaultdict(lambda: collections.defaultdict(list))

for name, dept, building in csvFile:
    data[building][dept].append(name)

buildings = data.keys()
buildings.sort()
for building in buildings:
    print "Building {0}".format(building)

    depts = data[building].keys()
    depts.sort()
    for dept in depts:
        print "  Dept {0}".format(dept)

        names = data[building][dept]
        names.sort()
        for name in names:
            print "   ",name
0

精彩评论

暂无评论...
验证码 换一张
取 消