1

I have a list of dictionary items stored in variable List_dicts, and I have to write a selected list of items from the above list into a file. given below my python function:

def write_items(List_dicts,key_list):
  #List_dicts contains the list if dicts
  #key_list contains the key separated by comma
  k_list=key_list.split(',')
  write_string=''
  for i in k_list:
    write_string=write_string+"item['"+i+"'],"
  f=open('log.txt','w')
  for item in List_dicts:
    f.write(write_string[0:len(write_string)-1]) #this should write item['key1'],item['key2'],item['key3']..,item['keyn'] not the value of string 'write_string'
  f.close()

Is this possible in anyways? I was inspired from SQL dynamic execute quires.

1
  • use csv with dictwriter Commented Apr 23, 2013 at 16:46

3 Answers 3

3

edit : judging from your code, your function doesn't appear to be writing anything related to the contents of dicts. you are writing write_string[0:len(write_string)-1] to your file for each dict you got(which is just a copy of your write_string without last trailing comma) and the write_string has nothing to with items in your dict, it's just selected keys from the key_list.

there is a python module, csv, with a class called DictWriter, which is suitable for your job.

import csv

def write_dicts(dicts, keys, filename):

   with open(filename, 'w') as csvfile:
       writer = csv.DictWriter(csvfile, keys, extrasaction='ignore')
       for d in dicts:
           writer.writerow(d)
Sign up to request clarification or add additional context in comments.

Comments

0

I'm not sure I understand the question, but if I do, here's what you should be using: http://docs.python.org/2/library/pickle.html

Basically it allows you to store python objects in files. Here's a quick example you should have a look at: http://wiki.python.org/moin/UsingPickle

Comments

0

Apart from being better off using the csv module, what you did wrong was that you overcomplicated things.

You already have a list of keys to write, so just loop directly over those keys:

def write_items(List_dicts, key_list):
    k_list = key_list.split(',')
    with open('log.txt','w') as f:
        for item in List_dicts:
          for key in k_list:
              f.write(item[key])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.