2015-04-06 25 views
-1

我有一個包含多個字典的文件,每行一個。 他們都有相同的密鑰。我想在所有這些中將一個關鍵字從'id'重命名爲'orderid'。什麼是最有效的方式呢?在多個字典中重命名密鑰

的樣本數據:

{'total_ex_tax': '11.0000', 'is_deleted': False, 'status_id': 5, 'id': 614534} 
{'total_ex_tax': '100.0000', 'is_deleted': False, 'status_id': 5, 'id': 614535} 

到目前爲止的代碼:

def popAndMergeDicts(dicts): 

    dictLine = ast.literal_eval(dicts) 
    tempDict = dictLine['billing_address'] 
    del dictLine['billing_address'] 
    for i in tempDict: 
     dictLine[i] = tempDict[i] 
    # insertOrdersInDatabase(dictLine) 
    rename_id(dictLine) 
    return dictLine 


def rename_id(dictionary): 

    pass 


def process_orders_file(filename): 

    lines = tuple(open(filename)) 
    for line in lines[0:]: 
     popAndMergeDicts(line) 

process_orders_file('allOrdersData') 
+0

你要編輯文件中的文字?還是你想在運行時動態改變名稱?如果是這樣,爲什麼? – Dannnno 2015-04-06 04:28:37

+0

您的文本編輯器可能具有查找和替換功能,或者您可以在運行時更改它,打印到文件,然後複製粘貼 – Dannnno 2015-04-06 04:35:17

+0

這是json嗎? – 2015-04-06 04:54:12

回答

0

這是微不足道的:

def rename_id(dictionary): 
    try: 
     dictionary['new_key'] = dictionary.pop('old_key') 
    except KeyError: 
     # 'old_key' is not present in dictionary. 
     if not dictionary.has_key('new_key'): 
      raise KeyError('This dictionary is missing "old_key": %s' % 
          dictionary) 

如果KeyError提高,搜索文件的錯誤造成的字典並根據需要進行更正。

+0

他需要編輯問題。該問題要求提供'rename_id'的代碼。爲什麼還有問題中的代碼呢? – dbliss 2015-04-06 04:37:11

+0

對不起,我想我說錯了。我真的想在運行時改變,我以爲你的意思是別的。我的錯。 – 2015-04-06 04:37:31

+0

得到這個:dictionary ['orderid'] = dictionary.pop('id') KeyError:'id' – 2015-04-06 04:41:18

-1

你想直接使用新的字典,如果沒有的話:如果你想使用它作爲字典

with open("input.txt") as f: 
    for line in f: 
     print(line.strip().replace("id", "orderid")) 

,那麼你可以嘗試:

import ast 
with open("input.txt") as f: 
    for line in f: 
     mydict = ast.literal_eval(line.strip()) 
     mydict["ordeid"] = mydict.pop("id") 
     # use mydict 
+0

這不會取代單詞id的任何出現,而不僅僅是那些特定的? – Dannnno 2015-04-06 04:36:58