2017-02-23 2 views
-4

私は以下の形式のサンプルファイルを複数の部分に分けて、キー "type"に関連付けられた値に基づいて別の辞書に格納する方法を理解しようとしています。この。ありがとう。キーに基づいて大きなファイルを分割し、ファイルを別の辞書にpythonを使って格納する方法はありますか?

[ 
{"type": "A", "verb": "NEW", "key": "96f55c7d8f42", "event_time": "2017-01-06:12:46:46.384Z", "last_name": "Smith", "adr_city": "Middletown", "adr_state": "AK"}, 
{"type": "B", "verb": "NEW", "key": "ac05e815502f", "event_time": "2017-01-06:12:45:52.041Z", "customer_id": "96f55c7d8f42", "tags": {"some key": "some value"}}, 
{"type": "C", "verb": "UPLOAD", "key": "d8ede43b1d9f", "event_time": "2017-01-06:12:47:12.344Z", "customer_id": "96f55c7d8f42", "camera_make": "Canon", "camera_model": "EOS 80D"}, 
{"type": "D", "verb": "NEW", "key": "68d84e5d1a43", "event_time": "2017-01-06:12:55:55.555Z", "customer_id": "96f55c7d8f42", "total_amount": "12.34 USD"} 
] 
~  

答えて

0

あなたはdata.txtされたファイルと仮定すると、これを試してみてください。

import json 

with open('data.txt') as data_file: 
    data = json.load(data_file) 

for row in data: 
    print("Type: " + row['type']) 
    print(row) 
    print() 
+0

データを別々のデータ構造に格納し、これらのデータ構造に適用する次の関数で使用します。 – Teja

+0

この次のコードを表示できますか?元の投稿を編集します。 –

+0

まだ書く必要がありますが、私が直面している問題は、type属性に基づいて別々の辞書にデータを格納することです。 – Teja

0

最も簡単な方法は、辞書の辞書である可能性があります。

各行を読み取るイテレータを書き、ujsonを使用してテキストを解析してdictにします。次にpopキーとして使用する値を返し、両方の部分を返します。

import ujson 

def read_lines(file_path): 
    with open(file_path, 'r') as fh: 
     for line in fh: 
      dictionary = ujson.loads(line) 
      key = dictionary.pop('key') 
      yield key, dictionary 


dictionaries = dict() 
for key, value in read_lines(r"/foo/bar/file.txt"): 
    dictionaries[key] = value 
関連する問題