1

I want something like following structure : y['1'][tuple(list)] = val as an nested dict in python but while i am trying i get KeyError :

data in csv file is like :

Rest_id, rates, items
1,4, burger
1,8, tofu_log
2,5, burger
2,8.5, tofu_log
3,4, chef_salad
3,8, steak_salad_sandwich
4,5, steak_salad_sandwich,salad
4,2.5, wine_spritzer
5,4, extreme_fajita3,test2,test4,test
5,8, fancy_european_water
6,5, fancy_european_water
6,6,  extreme_fajita, jalapeno_poppers, extra_salsa
7,1.5, wine_spritzer
7,5, extreme_fajita, jalapeno_poppers

following is the code :

y = defaultdict(dict)

with open('sample_data_tested_with.csv','r') as f:
            reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONE)
            reader = [[x.strip() for x in row] for row in reader]
            for i in reader:
                #cd[i[0]] = {tuple(i[2:]):i[1]}
                #cd[i[0]][tuple(i[2:])].update(i[1])
                print i[0], i[1], tuple(i[2:])
                y[i[0]][tuple(i[2:])].append(i[1])

Later I want to search in the dict like y['rest_id']['item'] and find rates for that. Thanks in advance.

full stack from ipython :

 In [49]: with open('sample_data_tested_with.csv','r') as f:
            reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONE)
            reader = [[x.strip() for x in row] for row in reader]
            for i in reader:
                #cd[i[0]] = {tuple(i[2:]):i[1]}
                #cd[i[0]][tuple(i[2:])].update(i[1])
                print i[0], i[1], tuple(i[2:])
                #x[tuple(i[2:])]=float(i[1])
                y[i[0]][tuple(i[2:])].append(i[1])
   ....:         
 1 4 ('burger',)
 ---------------------------------------------------------------------------
 KeyError                                  Traceback (most recent call last)
 <ipython-input-49-ab608c2dc33a> in <module>()
       7                     print i[0], i[1], tuple(i[2:])
       8                     #x[tuple(i[2:])]=float(i[1])
 ----> 9                     y[i[0]][tuple(i[2:])].append(i[1])
       10 

  KeyError: ('burger',)
1
  • i could have y = defaultdict(list) and append data but then im not able to search data based on the keys like : y['rest_id']['item'] Commented Feb 27, 2014 at 8:53

2 Answers 2

0

Looks like you could use itertools.groupby

>>>import itertools
>>>newreader,keys=[],[]
>>>for k,g in itertools.groupby(reader,key=lambda x:x[0]):
      newreader.append(tuple(g[1:]))
      keys.append(k)

This should group your data into tuples. Now we iterate through newreader converting each tuple into a dict.

>>>d={}
>>>for *i,j in newreader,keys:
     d[j]=dict(i)
Sign up to request clarification or add additional context in comments.

6 Comments

I am getting following error now : ValueError Traceback (most recent call last) <ipython-input-59-145e6ba39c9a> in <module>() ----> 1 for i,j in newreader,keys: 2 d[j] = dict(i) 3 ValueError: too many values to unpack
@snehalparmar thanks for the feedback, let me check.
@snehalparmar could you edit in the output your print statement gives into your original question?
@snehalparmar does the updated code work? I am using Cpython so I don't know if this is implementation specific.
@snehalparmar check now. if not, then I got nothing.
|
0

Here is the solution i got, please check and let know if anyones find any issues with it, thanks a lot.

def create_NestedDict(filename):
    NestedDict = defaultdict(dict)
    with open(filename,'rb') as f:
        reader = csv.reader(f, delimiter=',')
        for row in reader:
            #print "row :", row
            record = row
            if record[0] not in NestedDict:
                NestedDict[record[0]] = {}
            items = tuple([ i.strip() for i in record[2:]])
            [record[0]][items] = record[1]
    return NestedDict

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.