cps1
cps1

Reputation: 63

Create dictionary, only adding rows where one column matches a value in a list

I've got 2 CSV files.

First, I want to take 1 column and make a list.

Then I'd like to create a dictionary from another CSV, but only with rows where the value from one column matches a value already in the list created earlier on.

Here's the code so far:

#modified from: http://bit.ly/1iOS7Gu
import pandas
colnames = ['Gene > DB identifier', 'Gene_Symbol',  'Gene > Organism > Name', 'Gene > Homologues > Homologue > DB identifier',  'Homo_Symbol',  'Gene > Homologues > Homologue > Organism > Name',  'Gene > Homologues > Data', 'Sets > Name']
data = pandas.read_csv(raw_input("Enter csv file (including path)"), names=colnames)

filter = set(data.Homo_Symbol.values)

print set(data.Homo_Symbol.values)

#new_dict = raw_input("Enter Dictionary Name")
#source: http://bit.ly/1iOS0e3
import csv
new_dict = {}
with open('C:\Users\Chris\Desktop\gwascatalog.csv', 'rb') as f:
  reader = csv.reader(f)
  for row in reader:
      if row[0] in filter:
        if row[0] in new_dict:
            new_dict[row[0]].append(row[1:])
        else:
            new_dict[row[0]] = [row[1:]]
print new_dict

Here are the 2 sample data files: http://bit.ly/1hlpyTH

Any ideas? Thanks in advance.

Upvotes: 0

Views: 610

Answers (1)

ndpu
ndpu

Reputation: 22561

You can use collections.defaultdict to get rid of check for list in dict:

from collections import defaultdict

new_dict = defaultdict(list)
#...
   for row in reader:
      if row[0] in filter:
         new_dict[row[0]].append(row[1:])

Upvotes: 1

Related Questions