-1
fs = codecs.open('grammar_new.txt', encoding='utf-8')
unidata=[]
d={}
fr=codecs.open('rule.txt', 'w')
for line in fs:
    line_data=line.split()
    for i in range(0,len(line_data)):
       unidata.append(line_data[i])


d = defaultdict(unidata)

while executing this code will generate error as d = defaultdict(unidata) TypeError: first argument must be callable..I want to store duplicate keys in dictionary

leppie
  • 115,091
  • 17
  • 196
  • 297
Dhanya
  • 35
  • 1
  • 1
  • 6
  • 1
    Well, that's not how `defaultdict` works. But what do you want to be your keys (or alternatively, values)? You just have a `list` of strings... – roippi Jan 29 '14 at 05:21
  • Can you give a bit more detail on what the line data actually looks like and what you want as a response? – mgilson Jan 29 '14 at 05:22
  • Actually unidata is a list contain [[u'NP--->', u'N_NNP'], [u'NP--->', u'N_NN_S_NU'], [u'NP--->', u'N_NNP'], [u'NP--->', u'N_NNP'], [u'VGF--->', u'V_VM_VF'], [u'NP--->', u'N_NN']] I have to store these into dictionary. – Dhanya Jan 29 '14 at 05:33

2 Answers2

9

The first argument to defaultdict must be callable. You've passed an instance of list which isn't callable. You want to pass the 'list' type instead.

Typical use would be something like:

d = defaultdict(list)
for k, v in something:
    d[k].append(v)

Based on the unidata you seem to have provided in your comment, I think you want:

>>> from collections import defaultdict
>>> unidata = [[u'NP--->', u'N_NNP'], [u'NP--->', u'N_NN_S_NU'], [u'NP--->', u'N_NNP'], [u'NP--->', u'N_NNP'], [u'VGF--->', u'V_VM_VF'], [u'NP--->', u'N_NN']]
>>> d = defaultdict(list)
>>> for k, v in unidata:
...     d[k].append(v)
... 
>>> d
defaultdict(<type 'list'>, {u'VGF--->': [u'V_VM_VF'], u'NP--->': [u'N_NNP', u'N_NN_S_NU', u'N_NNP', u'N_NNP', u'N_NN']})
mooreds
  • 4,932
  • 2
  • 32
  • 40
mgilson
  • 300,191
  • 65
  • 633
  • 696
1

I want to store duplicate keys in dictionary

This is simply not possible. Keys in dictionaries are unique. I think what you want is this:

d = defaultdict(list)
with codecs.open('grammar_new.txt', encoding='utf-8') as f:
   for line in f:
      if len(line.rstrip()):
          key,value = line.rstrip().split()
          d[key].append(value)

print(d)

Now d will contain for each key a list that contains the corresponding values. Each key must be unique, but it can have any number of values, which can be duplicates.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284