简体   繁体   English

如何替换python列表中存在的字典中的键?

[英]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. 我想仅使用python替换python列表中存在的字典的键。 I have this 我有这个

Actual Data 实际数据

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

Expected result 预期结果

[{'Title':'Replace key','number':'Replacing Keys','Title':'Replaced Keys'}] In place of Title.1 I want Title [{'标题':'替换键','数字':'替换键','标题':'替换键'}]代替Title.1我想要标题

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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