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

Time:07-20

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!

CodePudding user response:

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.

CodePudding user response:

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'\s\b[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'}

CodePudding user response:

it looks a bit tricky and requires some extra memory but it seems working. needs to be tested:

import json
from re import sub

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

data = json.loads(sub(r'(\s\w)(?=[^,] ?:)', lambda m: m[1].upper().strip(), json.dumps(data)))

>>> data
'''
{'id': '4',
 'eventTitle': 'Coldplay World Tour',
 'eventStartDate': '29/07/202220:30',
 'eventEndDate': '30/07/202201: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'}
  • Related