简体   繁体   中英

How to replace keys in dictionary present in a python list?

I want to replace keys of the dictionary present in python list using python only. I have this

Actual Data

[{'Title.1':'Replace key','number':'Replacing Keys','Title.1':'Replaced Keys'}]

Expected result

[{'Title':'Replace key','number':'Replacing Keys','Title':'Replaced Keys'}] In place of Title.1 I want Title

 data = [{'Title.1':'Replace key','number':'Replacing 
             Keys','Title.1':'Replaced Keys'}]
for name, datalist in data.iteritems(): 
    for datadict in datalist:
        for key, value in datadict.items():
             if key == Title.1:
                datadict[key] = Title
             print (data)

Basicly if you want to change a key you need to create a new key with the desired name copy the data of the old key in it then remove the old key so for that you can use this code :

my_dictionnary = { "old_key": "my_value" }
my_dictionnary["new_key"] = my_dictionnary["old_key"]
del my_dictionnary["old_key"]

So in order to answer to the specific case that you show us you can do something like this :

datas = [{'Title.1':'Replace key','number':'Replacing 
             Keys','Title.1':'Replaced Keys'}]
for data in datas:
    for key in data:
        if key[-2:] == ".1":
            data[key[:-2]] = data[key]
            del data[key]

Here same key given two times ...dictionary keys must be unique

    for i in data:
        for k,v in i.items():
            if k=='Title.1':
                del i[k]
                i['Title'] = v
    print(data)
    #[{'number': 'Replacing Keys', 'Title': 'Replaced Keys'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM