Pergunta

I have the following data:

foo red test
foo red test
foo red test2
foo blue test
bar red test
bar blue test
bar red test2
bar red test2

What I want to do is to count the value above resulting in this dictionary of dictionary of dictionary :

{
   'bar' : {
              'blue' : {
                          'test': 1
                        },
               'red' : {
                          'test' : 1,
                          'test2': 2
                        }
                   },
          'foo' : {
                     'blue' : {
                                 'test' : 1
                               },
                     'red' => {
                                'test' : 2,
                                'test2' : 1
                              }
                   }
        }

Why the following code failed (I'm using Python 2.6.2)

from collections import defaultdict
dictfinal = defaultdict(lambda: defaultdict(dict))
with open('myfileabove.txt','r') as tsvfile:
    csvreader = csv.reader(tsvfile,delimiter=' ')
    for rw in csvreader:
        val1 = rw[0]
        val2 = rw[1]
        val3 = rw[2]
        dictfinal[val1][val2][val3] +=1

In Perl it could be done like this: https://eval.in/121318

Foi útil?

Solução

Change dict definition to:

dictfinal = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))

Outras dicas

As a complement, I would suggest a single dictionary instead of nested ones. It would scales better if you add columns to your csv.

from collections import Counter

a = """foo red test
foo red test
foo red test2
foo blue test
bar red test
bar blue test
bar red test2
bar red test2"""

b = Counter(tuple(s.split()) for s in a.splitlines())

# Counter({('foo', 'red', 'test'): 2, ('bar', 'red', 'test2'): 2, ('bar', 'blue', 'test'): 1, ('foo', 'blue', 'test'): 1, ('foo', 'red', 'test2'): 1, ('bar', 'red', 'test'): 1})
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top