重命名多个词典中的键

时间:2015-04-06 04:25:38

标签: python dictionary

我有一个包含多个词典的文件,每行一个。 他们都有相同的钥匙。我想在所有这些中将一个键从'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')

2 个答案:

答案 0 :(得分: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,请在文件中搜索导致错误的字典并根据需要进行更正。

答案 1 :(得分:-1)

您是否想直接使用新的dict,如果没有,那么:

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

如果您想将其用作dict,那么您可以尝试:

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