-1

I have a file with multiple dictionaries, one in each line. They all have the same keys. I want to rename one key from 'id' to 'orderid' in all of them. What is the most efficient way to do so?

Sample data:

{'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}

Code so far:

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 Answers2

0

This is trivial:

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)

If KeyError is raised, search your file for the error-causing dictionary and correct it as necessary.

abcd
  • 10,215
  • 15
  • 51
  • 85
-1

Do you want to use the new dict directly, if not then:

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

If you want to use it as dict, then you can try:

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
Rain Lee
  • 511
  • 2
  • 6
  • 11