how can i change all my key's name in my dictionnary

Question:

I have a dictionnary and i would like to rename all the keys with this patter (test number 1 => testNumber1)

there is my dict:

{'id': '4', 'event title': 'Coldplay World Tour', 'event start date': '29/07/2022 20:30', 'event end date': '30/07/2022 01:00', 'name of the location hosting the event (optional)': 'Stade de France', 'address of the location': '93200 Saint-Denis', 'total ticket number': '10000', 'maximum tickets per user': '6', 'sale start date': '04/05/2022', 'line up': '', 'asset url': 'https://coldplay.com/coldplay_asset.mp4'}

on another json -i have done these 2 elems:

self.json_informations[i]['smart_contract']['collectionName'] = self.json_informations[i]['smart_contract'].pop('collection name') #on remplace collection par collectionName

but it will be too long to change all the params (and its not really flexible).0

I tried a loop too but it didn’t work:

    for j in range(len(self.json_informations[0])): #my dict is in json_informations[0]
                    print(self.json_informations[0][j])

but it gives me an error

    print(self.json_informations[i][j])
KeyError: 0

i would like to get this result as my output

{'id': '4', 'eventTitle': 'Coldplay World Tour', 'eventStartDate': '29/07/2022 20:30', 'eventEndDate': '30/07/2022 01:00', 'nameOfTheLocation': 'Stade de France', 'addressOfTheLocation': '93200 Saint-Denis', 'totalTicketNumber': '10000', 'maximumTicketsPerUser': '6', 'saleStartDate': '04/05/2022', 'lineUp': '', 'assetUrl': 'https://coldplay.com/coldplay_asset.mp4'}

thanks for yours answers!

Asked By: guiguilecodeur

||

Answers:

The only problem in your loop is that you’re looping over the dict in the wrong manner. The way looping over a dict is as follows:

mydict = {"Hi": 1, "there": 2, "fellow": 3}

for key in mydict:
    print(key)

will have an output of:

Hi
there
fellow

Because looping over a dictionary gives you the keys themselves as the loop variable. You were attempting in your loop to loop over integer numbers and access a dictionary value corresponding to said integer value key, but trying to access the item corresponding to a key obviously gives an error if said key doesn’t exist. So to change the names of keys in a dictionary in a loop you would use a loop such as:

mydict = {"Hi": 1, "there": 2, "fellow": 3}

for key in mydict:
    mydict[newkey] = mydict.pop(key)

Which you will notice to be similar to how you did it in the first place, now just over a loop.

Answered By: Otto Hanski

I Think this is exact solution which you are looking for:

import re
input_data = {'id': '4',
     'event title': 'Coldplay World Tour',
     'event start date': '29/07/2022 20:30',
     'event end date': '30/07/2022 01:00',
     'name of the location hosting the event (optional)': 'Stade de France',
     'address of the location': '93200 Saint-Denis',
     'total ticket number': '10000',
     'maximum tickets per user': '6',
     'sale start date': '04/05/2022',
     'line up': '',
     'asset url':'https://coldplay.com/coldplay_asset.mp4'}

copy_a = input_data.copy()
for key, value in copy_a.items():
    # print(x.title())
    if ' ' in key:
        # match string with regex
        new_str = re.sub(r'sb[a-z]', lambda m: m.group().upper(), key)
        # replace 1st char of word to upper case except 1st word
        new_key = new_str.replace(" ", "")
        input_data[new_key] = input_data[key]
        # delete key from input_data
        del input_data[key]

print(input_data)

Output:

{'id': '4', 'eventTitle': 'Coldplay World Tour', 'eventStartDate': '29/07/2022 20:30', 'eventEndDate': '30/07/2022 01:00', 'nameOfTheLocationHostingTheEvent(optional)': 'Stade de France', 'addressOfTheLocation': '93200 Saint-Denis', 'totalTicketNumber': '10000', 'maximumTicketsPerUser': '6', 'saleStartDate': '04/05/2022', 'lineUp': '', 'assetUrl': 'https://coldplay.com/coldplay_asset.mp4'}
Answered By: Hiral Talsaniya
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.