1

I have a csv file in the following format:

age,name
3,abc
5,xyz
6,pqr
4,stu
8,lkm

How can I put this in a dictionary in the following format:

{3:'abc', 5:'xyz', 6:'pqr', 4:'stu', 8:'lkm'}

UPDATE:

mycode-

age_file = open('age.csv','r')
csv_age = csv.DictReader(age_file)

for row in csv_age:
    print(row)

OUTPUT:

{'age' : 3, 'name' : 'abc', 'age' : 5, 'name' : xyz, ... }
Luke
  • 79
  • 1
  • 8
  • 1
    Are you guaranteed not to have any entries with duplicate ages? – mgilson Nov 24 '15 at 22:23
  • follow up to that question: are you sure you dont want the key/values switched so that the name maps to their age? – R Nar Nov 24 '15 at 22:24
  • I could not post the entire file and i apologize for not pointing that out but yes, there will be duplicate value. But that does not mean i will only append one of those. If my file has 3,3,3 as age then i will have 3,3,3 in my dictionary as a key also and the value will be the corresponding name. – Luke Nov 24 '15 at 22:25
  • @RicardoCárdenes i tried those methods but i keep getting an error saying that list object can only be int, or slices and not str. – Luke Nov 24 '15 at 22:28
  • @RNar I don't mind if the key/values are switched. My main goal is to put this information in a dictionary such that i have a key and a value. Probably key being the age and value being the name – Luke Nov 24 '15 at 22:30
  • @Luke how did you try those methods? that error sounds really strange to me... – R Nar Nov 24 '15 at 22:31
  • @Luke without seeing what you have tried before, we cannot know. So far, your question is a duplicate of dozen others. Please, provide code and then we can point you out to the problem. – Ricardo Cárdenes Nov 24 '15 at 22:31
  • @RicardoCárdenes i updated it with my code. – Luke Nov 24 '15 at 22:43
  • @Luke So you're reading the file using `cvs.DictReader`, which is legit. Then you iterate over the rows. For each row you get a dictionary `{'age': , 'name': }`. You can build a new dictionary, entry by entry, by taking those values. I still don't see where you could get the error you mention. It would be useful to see the piece of code that gives you *that* – Ricardo Cárdenes Nov 24 '15 at 22:47
  • 1
    @RicardoCárdenes alright i got it!! i used .strip().split() method and did something like my_dict = { age : number } Thansk for all the help! – Luke Nov 24 '15 at 23:03
  • Good. You could have used the results from `csv.DictReader`, though (or `csv.reader`, for that matter). – Ricardo Cárdenes Nov 24 '15 at 23:05

2 Answers2

1

Except problem came from age and name. If name/age are uniq, you can use :

import csv
my_result={}
with open('age.csv', 'rb') as csvfile:
     for age,name in csv.reader(csvfile, delimiter=','):
         my_result[age]=name

but I hope a defaultdict better for your use. And make it more robust from having more than one name for one age:

import csv
from collection import defaultdict 
my_result=defaultdict(list)
with open('age.csv', 'rb') as csvfile:
     for row in csv.reader(csvfile, delimiter=','):
         my_result[age].append(name)

In this case, the result will be: {1:["bob","john"],3:["bill"],6:["Georges","Monica"]}

A.H
  • 1,007
  • 5
  • 15
  • for part two of your code, shell gives me an error saying that dict object has no attribute append. – Luke Nov 24 '15 at 22:55
0

I'm lazy so I use pandas:

import pandas as pd
df = pd.read_csv('test.csv')
dd = {}
for ii, age in enumerate(df.age):
    dd[age] = df.name.iloc[ii]

However, I agree with the comments above that you'll clobber previous entries that have a given age as a key the next time that same age shows up as a key.

dslack
  • 835
  • 6
  • 17