0

I have a dict. There are about 10,000 key:value pairs in this dict.

I want to write these pairs(just as strings) 1-100 to a file, then pairs 101-200 to a second file, then 201-300 to a third file etc.

How would one do that in python?

Wilson Mak
  • 147
  • 3
  • 12

1 Answers1

1

The iteration methods is based on Iterating over dictionaries using 'for' loops

c = 0
f = open('%d.txt'%(c),'w')
for key, value in d.iteritems():
    print>>f,"%s:%s"%(str(key),str(value))
    c += 1
    if c % 100 == 0:
        f.close()
        f = open('%d.txt'%(c/100),'w')
f.close()
Community
  • 1
  • 1
William
  • 598
  • 4
  • 10
  • Note that this works for Python2. If in Python3, you'll need to use `d.items()` to iterate over the key-value pairs of the dictionary (in addition to using parentheses for the `print` function). – code_dredd Aug 27 '15 at 01:05