0

I have created dictionary object my parsing a json file in python....lets assume the data is as follows

    plants = {}  

# Add three key-value tuples to the dictionary.
plants["radish"] = {"color":"red", "length":4} 
plants["apple"] = {"smell":"sweet", "season":"winter"}
plants["carrot"] = {"use":"medicine", "juice":"sour"}

This could be a very long dictionary object

But at runtime, I need only few values to be stored in a commaa delimited csv file.....The list of properties desired is in a file.... e.g

radish.color
carrot.juice

So, how would I create in python an app, where I can created dynamic variables such as below to get data of the json object & create a csv file....

at runtime i need variable

plants[radish][color]
plants[carrot][juice]

Thank you to all who help

Sanjay

3
  • 2
    What's wrong with plants['radish']['color'] ? Commented Aug 11, 2016 at 17:18
  • How do you create variable DYNAMICALLY at runtime in pythin code .....if I have 100 such combinations of radish.color or carrot.juice or mango.season in a file ....How would I write code to fetch the above values at runtime from the dictionary object, by reading the strings radish.color , carrot.juice , mango.season from an external file... As asked by depperm...I havent tried it, as am not aware how to solve it Commented Aug 11, 2016 at 17:30
  • The list of variable I need to fetch from dictionary object vary.....some are 1 level deep, or 2 levels, 3 or further.....such as radish radish.color watermellon.season.fertilizer I need to fetch values of above set of variables & export to a csv file Commented Aug 11, 2016 at 17:36

1 Answer 1

1

Consider parsing the text file line by line to retrieve file contents. In the read, split the line by period which denotes the keys of dictionaries. From there, use such a list of keys to retrieve dictionary values. Then, iteratively output values to csv, conditioned by number of items:

Txt file

radish.color 
carrot.juice

Python code

import csv

plants = {}  
plants["radish"] = {"color":"red", "length":4} 
plants["apple"] = {"smell":"sweet", "season":"winter"}
plants["carrot"] = {"use":"medicine", "juice":"sour"}

data = []
with open("Input.txt", "r") as f:
    for line in f:
        data.append(line.replace("\n", "").strip().split("."))

with open("Output.csv", "w") as w:
    writer = csv.writer(w,  lineterminator = '\n')

    for item in data:            
        if len(item) == 2:   # ONE-NEST DEEP
            writer.writerow([item[0], item[1], plants[item[0]][item[1]]])
        if len(item) == 3:   # SECOND NEST DEEP
            writer.writerow([item[0], item[1], item[2], plants[item[0]][item[1]][item[2]]])

Output csv

radish,color,red
carrot,juice,sour

(Note: the deeper the nest, the more columns will output conflicting with key/value pairs across columns -maybe output different structured csv files like one-level files/second-level files)

Sign up to request clarification or add additional context in comments.

4 Comments

Parfait: You have a very good solution..I was only hoping if the multiple if clauses could be avoided & soultion automated as we know the len(items) One thing I have been trying is to use eval( plants[item[0]][item[1]]]) function and keep appending to the key as follows
#each_property is list of keys in file ( . delimited ) #each_property = radish.color #each_property = watermellon.season.fertilizer
for sdr in data: csvString='' for each_property in the_properties_list: thekeys = each_property.split(".") i =0 for thekey in thekeys: if (i==0): fullkey="sdr[" + "\"" + thekey + "\"" + "]" else: fullkey=fullkey + "[" + "\"" + thekey + "\"" + "]" i=i+1 try: csvString=csvString + "\t" + eval( "'" + fullkey + "'") except Error: csvString=csvString + "\t" + ''
Anticipating different levels of nested dictionaries for any possibility might involve nested loops or list comprehensions/generators or even a recursive function. Consider anticipating length as this simpler solution does or go another route.

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.