嵌套的dict python键

时间:2014-02-27 07:09:10

标签: python dictionary nested key

我想要以下结构: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',)

2 个答案:

答案 0 :(得分: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将每个元组转换为dict。

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

答案 1 :(得分: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