2013-10-30 173 views
0

我想拆分鍵和值並顯示下面提到的格式的字典結果。我正在閱讀一個文件並將數據分成列表,然後轉移到字典中。拆分字典鍵和字典值的列表

請幫我拿到結果。

輸入文件 - commands.txt中

login url=http://demo.url.net [email protected] password=mytester 

create-folder foldername=demo 

select-folder foldername=test123 

logout 

預期結果格式

print result_dict 


     "0": { 
      "login": [ 
       { 
        "url": "http://demo.url.net", 
        "username": "[email protected]", 
        "password": "mytester" 
       } 
      ] 
     }, 
     "1": { 
      "create-folder": { 
       "foldername": "demo" 
      } 
     }, 
     "2": { 
      "select-folder": { 
       "foldername": "test-folder" 
      } 
     }, 
     "3": { 
      "logout": {} 
     } 

CODE

file=os.path.abspath('catalog/commands.txt') 
    list_output=[f.rstrip().split() for f in open(file).readlines()] 
    print list_output 

    counter=0 
    for data in list_output: 
     csvdata[counter]=data[0:] 
     counter=counter+1 
    print csvdata 

for key,val in csvdata.iteritems(): 
    for item in val: 
     if '=' in item: 
      key,value=item.split("=") 
      result[key]=value 

print result 
+1

看起來你正在嘗試創建JSON。使用內置'json'模塊來完成該任務。 –

+1

咋,但他首先需要在這個字典中正確的數據。 – RickyA

+0

爲什麼'login'是預期結果中的一系列字符? –

回答

2

作爲一個功能:

from collections import defaultdict 
from itertools import count 

def read_file(file_path): 
    result = defaultdict(dict) 
    item = count() 
    with open(file_path) as f: 
     for line in f: 
      if not line: 
       continue 
      parts = line.split() 
      result[next(item)][parts[0]] = dict(p.split('=') for p in parts[1:]) 
    return dict(result) 

更好的例子和說明:

s = """ 
login url=http://demo.url.net [email protected] password=mytester 

create-folder foldername=demo 

select-folder foldername=test123 

logout 
""" 

from collections import defaultdict 
from itertools import count 

result_dict = defaultdict(dict) 
item = count() 

# pretend you opened the file and are reading it line by line 
for line in s.splitlines(): 
    if not line: 
     continue # skip empty lines 
    parts = line.split() 
    result_dict[next(item)][parts[0]] = dict(p.split('=') for p in parts[1:]) 

漂亮的印刷:

>>> pprint(dict(result_dict)) 
{0: {'login': {'password': 'mytester', 
       'url': 'http://demo.url.net', 
       'username': '[email protected]'}}, 
1: {'create-folder': {'foldername': 'demo'}}, 
2: {'select-folder': {'foldername': 'test123'}}, 
3: {'logout': {}}} 
+0

該代碼對我更有幫助並且實現相同。我想要更多的信息,如何提取密鑰,值和存儲到txt文件。我創建了以下邏輯來獲取所需的信息,如用戶名,網址,密碼,創建文件夾和寫入txt文件。 'code' def extract_value(dict_in,dict_out):for key,dict_in.iteritems()中的值:if isinstance(value,dict):extract_value(value,dict_out)else:dict_out [key] = value返回字典(dict_out) code'。代碼正在提取但已經存在鍵:值將被最新的迭代值替換。我怎樣才能避免這種情況。 – raj

+0

你應該問另一個問題,儘可能詳細。 –

1
lines = ["login url=http://demo.url.net [email protected] password=mytester", 
     "create-folder foldername=demo", 
     "select-folder foldername=test123", 
     "logout"] 

result = {} 
for no, line in enumerate(lines): 
    values = line.split() 
    pairs = [v.split('=') for v in values[1:]] 
    result[str(no)] = {values[0]: [dict(pairs)] if len(pairs) > 1 else dict(pairs)} 

import pprint 
pprint.pprint(result) 

輸出:

{'0': {'login': [{'password': 'mytester', 
        'url': 'http://demo.url.net', 
        'username': '[email protected]'}]}, 
'1': {'create-folder': {'foldername': 'demo'}}, 
'2': {'select-folder': {'foldername': 'test123'}}, 
'3': {'logout': {}}} 

但是你確定你需要的login值內多餘的名單?如果沒有,只需將[dict(pairs)] if len(pairs) > 1 else dict(pairs)更改爲dict(pairs)即可。

0
r = dict() 
f = open('commands.txt') 

for i, line in enumerate(f.readlines()): 
    r[str(i)] = dict() 
    actions = line.split() 
    list_actions = {} 
    for action in actions[1:]: 
    if "=" in action: 
     k, v = action.split('=') 
     list_actions[k] = v 
    if len(actions[1:]) > 1: 
    r[str(i)][actions[0]] = [list_actions] 
    else: 
    r[str(i)][actions[0]] = list_actions 


print r 

應該是工作

+0

你應該確保在你的代碼末尾使用'f.close()',或者使用推薦的'with open(FILE)'作爲f'方法。 –