ashakshan
ashakshan

Reputation: 479

replacing keys from a dictionary inside a list python

I have a list inside a nested dictionary

body = {'Ready Date': '2020-01-31T12:00:00','Shipment Line List': [{'Description': 'Test', 'Weigth': '5', 
        'Height': '4.0','Length': '2.0', 'Width': '3.0'}, {'Description': 'Test', 'Weigth': '20', 'Height': '5',
        'Length': '30', 'Width': '10']}

I want to iterate over the keys in the nested dictionary and replace "Weigth" with the correct spelling "Weight" I tried this approach, but I am not getting the expected output

key = {"Weigth":"Weight"}
def find_replace(dict_body, dictionary):
    # is the item in the dict?
    for item in dict_body:
        # iterate by keys
        if item in dictionary.keys():
            # look up and replace
            dict_body = dict_body.replace(item, dictionary[item])
    # return updated dict
    return dict_body

a = find_replace(body,key)
print(a)

Upvotes: 0

Views: 69

Answers (2)

Celius Stingher
Celius Stingher

Reputation: 18367

I think a better idea in this particular case is to treat everything as a string, replace and back as a dictionary. Because if you have multiple nested keys, it might be just be easier this way in two lines of code:

from ast import literal_eval
body = literal_eval(str(body).replace("Weigth","Weight"))

This outputs:

{'Ready Date': '2020-01-31T12:00:00',
 'Shipment Line List': [{'Description': 'Test',
   'Height': '4.0',
   'Length': '2.0',
   'Weight': '5',
   'Width': '3.0'},
  {'Description': 'Test',
   'Height': '5',
   'Length': '30',
   'Weight': '20',
   'Width': '10'}]}

Upvotes: 2

balderman
balderman

Reputation: 23815

I want to iterate over the keys in the nested dictionary and replace "Weigth" with the correct spelling "Weight"

something like the below

body = {'Ready Date': '2020-01-31T12:00:00', 'Shipment Line List': [{'Description': 'Test', 'Weigth': '5',
                                                                     'Height': '4.0', 'Length': '2.0', 'Width': '3.0'},
                                                                    {'Description': 'Test', 'Weigth': '20',
                                                                     'Height': '5',
                                                                     'Length': '30', 'Width': '10'}]}
for entry in body['Shipment Line List']:
    entry['Weight'] = entry['Weigth']
    del entry['Weigth']
print(body)

output

{'Ready Date': '2020-01-31T12:00:00', 'Shipment Line List': [{'Description': 'Test', 'Height': '4.0', 'Length': '2.0', 'Width': '3.0', 'Weight': '5'}, {'Description': 'Test', 'Height': '5', 'Length': '30', 'Width': '10', 'Weight': '20'}]}

Upvotes: 1

Related Questions