2014-02-27 200 views
1

我想是以下結構:y['1'][tuple(list)] = val 作爲一個Python嵌套字典,但同時,我努力,我得到KeyError:在csv文件嵌套字典蟒蛇鍵

的數據是這樣的:

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 

以下是代碼:

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]) 

後來我想在這樣的y['rest_id']['item']字典搜索並找到該利率。 在此先感謝。

從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',) 
+0

我能有Y = defaultdict(列表)和追加數據,但隨後林不能夠基於諸如鍵搜索數據:Y [「rest_id」] [「項目」] –

回答

0

看起來你可以使用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) 

這應該您的數據組到元組。 現在我們遍歷newreader將每個元組轉換爲字典。

>>>d={} 
>>>for *i,j in newreader,keys: 
    d[j]=dict(i) 
+0

我現在收到以下錯誤:ValueError Traceback(最近呼叫最後一個) in () ----> 1 for i,j in newreader,keys: 2 d [j] = dict(i) ValueError:太多的值來解壓 –

+0

@snehalparmar感謝您的反饋,讓我檢查。 – Guy

+0

@snehalparmar你能在輸出中編輯你的打印語句給你的原始問題嗎? – Guy

0

下面是我得到的解決方案,請檢查並讓我們知道是否有人發現任何問題,非常感謝。

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