2016-08-11 8 views
0

辞書オブジェクトからデータをフェッチするために....作成ランタイム変数は、私は私はPythonでJSONファイルを解析辞書オブジェクトを作成した

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"} 

これは非常に長くなる可能性を次のようにデータがあると仮定することができます辞書オブジェクト

しかし、実行時に、私はcommaa区切りのCSVファイルに格納するだけでいくつかの値を必要とする.....プロパティのリストが目的のファイルである.... 例えば

radish.color 
carrot.juice 

だから、私は、実行時にpythonで私は&は、CSVファイルを作成するJSONオブジェクトのデータを取得するには、以下のような動的変数を作成することができ、アプリ、....

を作成する方法を私は変数必要

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

サンジャイ

+2

'と間違って何植物['radish'] ['color'] '? – DeepSpace

+0

実行時にpythinコードで変数DYNAMICALLYを作成するにはどうすればいいですか?radish.colorやcarrot.juiceやmango.seasonのような100個の組み合わせがファイル内にある場合はどうすればいいですか?上記の値は、実行時に辞書オブジェクトから文字列radish.color、carrot.juice、mango.seasonを外部ファイルから読み取ることによって得られます。deppermによって尋ねられたように...私はそれを試していません。それは – sshroff

+0

辞書オブジェクトからフェッチする必要がある変数のリストは異なります。いくつかは1レベル深い、または2レベル、3以上など..... 大根 radish.color watermellon.season .pertilizer 上記の変数の値をフェッチして、CSVファイルにエクスポートする必要があります。 – sshroff

答えて

1

を助けるすべての人に感謝してファイルの内容を取得するためのラインで、テキストファイルの行を解析することを検討してください。読み込みでは、辞書のキーを示すピリオドで行を分割します。そこから、そのようなキーのリストを使用して辞書値を取得します。項目の数によって調整CSVに続いて、繰り返し出力値、:

txtがファイル

radish.color 
carrot.juice 

のPythonコード

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]]]) 

出力 CSV

radish,color,red 
carrot,juice,sour 

(注:複数の列が出力列にわたって、キー/値のペアと競合します巣深いが、1レベルのファイル/秒レベルのファイルのような出力の異なる構造化されたCSVファイルを-maybe)

+0

パフェット:あなたは非常に良い解決策を持っています。複数のif節を避けることができ、私たちがlen(items)を知っているので自動化することができます 私が試したことの一つは、eval(plants [item [0]] [item [1]]))関数を使用して、 – sshroff

+0

#each_propertyは、ファイル内のキーのリストです(。区切り) #each_property = radish.color #each_property = watermellon.season。 csvString = '' the_properties_listでeach_propertyため :データにおけるSDRのための肥料 – sshroff

+0

thekeys = each_property.split( "") I thekeysでthekeyため= 0 : IF(I == 0): fullkey = "sdr [" + "\" "+ thekey +" \ "" + "]" else: fullkey = fullkey + "[" + "+" \ "" + "]" = 0 + 1 try: csvString = csvString + "\ t" + eval( "'" + "フルキー+"' ") csvString = csvString +" \ t "+ '' – sshroff

関連する問題