Python 修改dict键并分配给新dict

Python 修改dict键并分配给新dict,python,Python,我有一个包含多个字典的列表形式的JSON数据。我想创建一个与旧字典值相同但键不同的新字典。我把原来的关键和删除下划线,以及大写每个字。问题是,当我创建新字典时,它不会在同一个庄园中创建字典(请参见下面的代码输出) 如何创建与旧词典结构相同但具有修改键的新词典 JSON数据 contacts_to_parse = [ { "contact_order": "1", "contact_type": "Other", "contact_role"

我有一个包含多个字典的列表形式的JSON数据。我想创建一个与旧字典值相同但键不同的新字典。我把原来的关键和删除下划线,以及大写每个字。问题是,当我创建新字典时,它不会在同一个庄园中创建字典(请参见下面的代码输出)

如何创建与旧词典结构相同但具有修改键的新词典

JSON数据

contacts_to_parse = [
    {
        "contact_order": "1",
        "contact_type": "Other",
        "contact_role": "role here",
        "contact_text": "contact text here"
    },
    {
        "contact_order": "2",
        "contact_type": "Mail Alias",
        "contact_role": "role here",
        "contact_text": "contact text here"
    },
    {
        "contact_order": "3",
        "contact_type": "Mail Alias",
        "contact_role": "role here",
        "contact_text": "contact text here"
    },
    {
        "contact_order": "5",
        "contact_type": "Other",
        "contact_role": "role here",
        "contact_text": "contact text here"
    },
    {
        "contact_order": "7",
        "contact_type": "Employee",
        "contact_role": "role here",
        "contact_text": "contact text here"
    },
    {
        "contact_order": "8",
        "contact_type": "Employee",
        "contact_role": "role here",
        "contact_text": "contact text here"
    },
    {
        "contact_order": "9",
        "contact_type": "Other",
        "contact_role": "role here",
        "contact_text": "contact text here"
    }
]
到目前为止的代码:

def check(contacts):
    parsed_keys = []
    new_dict = {}
    for contact in contacts:
        for key, val in contact.items():
            rm_underscore_capitalize = key.replace('_', ' ').title()
            new_dict[rm_underscore_capitalize] = val
            if rm_underscore_capitalize in new_dict:
                parsed_keys.append(new_dict)
                new_dict = dict()

    return parsed_keys


if __name__ == '__main__':
    con = check(contacts_to_parse)
    print(con)
[{'Contact Order': '1'}, {'Contact Type': 'Other'}, {'Contact Role': 'role here'}, {'Contact Text': 'contact text here'}, {'Contact Order': '2'}, {'Contact Type': 'Mail Alias'}, {'Contact Role': 'role here'}, {'Contact Text': 'contact text here'}, {'Contact Order': '3'}, {'Contact Type': 'Mail Alias'}, {'Contact Role': 'role here'}, {'Contact Text': 'contact text here'}, {'Contact Order': '5'}, {'Contact Type': 'Other'}, {'Contact Role': 'role here'}, {'Contact Text': 'contact text here'}, {'Contact Order': '7'}, {'Contact Type': 'Employee'}, {'Contact Role': 'role here'}, {'Contact Text': 'contact text here'}, {'Contact Order': '8'}, {'Contact Type': 'Employee'}, {'Contact Role': 'role here'}, {'Contact Text': 'contact text here'}, {'Contact Order': '9'}, {'Contact Type': 'Other'}, {'Contact Role': 'role here'}, {'Contact Text': 'contact text here'}]
电流输出:

def check(contacts):
    parsed_keys = []
    new_dict = {}
    for contact in contacts:
        for key, val in contact.items():
            rm_underscore_capitalize = key.replace('_', ' ').title()
            new_dict[rm_underscore_capitalize] = val
            if rm_underscore_capitalize in new_dict:
                parsed_keys.append(new_dict)
                new_dict = dict()

    return parsed_keys


if __name__ == '__main__':
    con = check(contacts_to_parse)
    print(con)
[{'Contact Order': '1'}, {'Contact Type': 'Other'}, {'Contact Role': 'role here'}, {'Contact Text': 'contact text here'}, {'Contact Order': '2'}, {'Contact Type': 'Mail Alias'}, {'Contact Role': 'role here'}, {'Contact Text': 'contact text here'}, {'Contact Order': '3'}, {'Contact Type': 'Mail Alias'}, {'Contact Role': 'role here'}, {'Contact Text': 'contact text here'}, {'Contact Order': '5'}, {'Contact Type': 'Other'}, {'Contact Role': 'role here'}, {'Contact Text': 'contact text here'}, {'Contact Order': '7'}, {'Contact Type': 'Employee'}, {'Contact Role': 'role here'}, {'Contact Text': 'contact text here'}, {'Contact Order': '8'}, {'Contact Type': 'Employee'}, {'Contact Role': 'role here'}, {'Contact Text': 'contact text here'}, {'Contact Order': '9'}, {'Contact Type': 'Other'}, {'Contact Role': 'role here'}, {'Contact Text': 'contact text here'}]

您需要将内部循环末尾附近的一些处理拉到外部循环。您试图循环使用一系列字典,然后循环使用键来更新
新字典
,但您太频繁地重新定义
新字典
。试试这个:

def check(contacts):
    parsed_keys = []
    for contact in contacts:
        new_dict = {}
        for key, val in contact.items():
            rm_underscore_capitalize = key.replace('_', ' ').title()
            new_dict[rm_underscore_capitalize] = val
        parsed_keys.append(new_dict)

    return parsed_keys

你的逻辑有点错误。要将条件移动到第二个for循环之外:

def check(contacts):
    parsed_keys = []
    new_dict = {}
    for contact in contacts:
        for key, val in contact.items():
            rm_underscore_capitalize = key.replace('_', ' ').title()
            new_dict[rm_underscore_capitalize] = val
        if rm_underscore_capitalize in new_dict:
            parsed_keys.append(new_dict)
            new_dict = dict()

    return parsed_keys

返回:

[
{'Contact Order': '1', 'Contact Type': 'Other',      'Contact Role': 'role here', 'Contact Text': 'contact text here'}, 
{'Contact Order': '2', 'Contact Type': 'Mail Alias', 'Contact Role': 'role here', 'Contact Text': 'contact text here'}, 
{'Contact Order': '3', 'Contact Type': 'Mail Alias', 'Contact Role': 'role here', 'Contact Text': 'contact text here'}, 
{'Contact Order': '5', 'Contact Type': 'Other',      'Contact Role': 'role here', 'Contact Text': 'contact text here'}, 
{'Contact Order': '7', 'Contact Type': 'Employee',   'Contact Role': 'role here', 'Contact Text': 'contact text here'}, 
{'Contact Order': '8', 'Contact Type': 'Employee',   'Contact Role': 'role here', 'Contact Text': 'contact text here'}, 
{'Contact Order': '9', 'Contact Type': 'Other',      'Contact Role': 'role here', 'Contact Text': 'contact text here'}
]

你预料到了吗?我试着让它变得简单

contacts_to_parse = [
    {
        "contact_order": "1",
        "contact_type": "Other",
        "contact_role": "role here",
        "contact_text": "contact text here"
    },
    {
        "contact_order": "2",
        "contact_type": "Mail Alias",
        "contact_role": "role here",
        "contact_text": "contact text here"
    }
]


def check(contacts):
    result = []
    for item in contacts:
        result.append({})
        for key, val in item.items():
            result[-1][key.replace('_', ' ').title()] = val
    return result


print(check(contacts_to_parse))
结果:

[
    {
        'Contact Order': '1',
        'Contact Type': 'Other',
        'Contact Role': 'role here',
        'Contact Text': 'contact text here'
    },
    {
        'Contact Order': '2',
        'Contact Type': 'Mail Alias',
        'Contact Role': 'role here',
        'Contact Text': 'contact text here'
    }
]
[{'Contact Order': '1',
  'Contact Role': 'role here',
  'Contact Text': 'contact text here',
  'Contact Type': 'Other'},
 {'Contact Order': '2',
  'Contact Role': 'role here',
  'Contact Text': 'contact text here',
  'Contact Type': 'Mail Alias'},
 {'Contact Order': '3',
  'Contact Role': 'role here',
  'Contact Text': 'contact text here',
  'Contact Type': 'Mail Alias'},
 {'Contact Order': '5',
  'Contact Role': 'role here',
  'Contact Text': 'contact text here',
  'Contact Type': 'Other'},
 {'Contact Order': '7',
  'Contact Role': 'role here',
  'Contact Text': 'contact text here',
  'Contact Type': 'Employee'},
 {'Contact Order': '8',
  'Contact Role': 'role here',
  'Contact Text': 'contact text here',
  'Contact Type': 'Employee'},
 {'Contact Order': '9',
  'Contact Role': 'role here',
  'Contact Text': 'contact text here',
  'Contact Type': 'Other'}]

您可以利用列表和dict理解:

contacts_to_parse = [
    {
        "contact_order": "1",
        "contact_type": "Other",
        "contact_role": "role here",
        "contact_text": "contact text here"
    },
    {
        "contact_order": "2",
        "contact_type": "Mail Alias",
        "contact_role": "role here",
        "contact_text": "contact text here"
    },
]

from pprint import pprint

pprint([{k.replace('_', ' ').title():v for k, v in contact.items()} for contact in contacts_to_parse])
印刷品:

[{'Contact Order': '1',
  'Contact Role': 'role here',
  'Contact Text': 'contact text here',
  'Contact Type': 'Other'},
 {'Contact Order': '2',
  'Contact Role': 'role here',
  'Contact Text': 'contact text here',
  'Contact Type': 'Mail Alias'}]

您可以使用列表理解和dict理解简化代码:

def check(contacts):
    return [_check_contact(contact) for contact in contacts]

def _check_contact(contact):
    return {key.replace('_', ' ').title(): value for key, value in contact.items()}

from pprint import pprint
pprint (check(contacts_to_parse))
结果:

[
    {
        'Contact Order': '1',
        'Contact Type': 'Other',
        'Contact Role': 'role here',
        'Contact Text': 'contact text here'
    },
    {
        'Contact Order': '2',
        'Contact Type': 'Mail Alias',
        'Contact Role': 'role here',
        'Contact Text': 'contact text here'
    }
]
[{'Contact Order': '1',
  'Contact Role': 'role here',
  'Contact Text': 'contact text here',
  'Contact Type': 'Other'},
 {'Contact Order': '2',
  'Contact Role': 'role here',
  'Contact Text': 'contact text here',
  'Contact Type': 'Mail Alias'},
 {'Contact Order': '3',
  'Contact Role': 'role here',
  'Contact Text': 'contact text here',
  'Contact Type': 'Mail Alias'},
 {'Contact Order': '5',
  'Contact Role': 'role here',
  'Contact Text': 'contact text here',
  'Contact Type': 'Other'},
 {'Contact Order': '7',
  'Contact Role': 'role here',
  'Contact Text': 'contact text here',
  'Contact Type': 'Employee'},
 {'Contact Order': '8',
  'Contact Role': 'role here',
  'Contact Text': 'contact text here',
  'Contact Type': 'Employee'},
 {'Contact Order': '9',
  'Contact Role': 'role here',
  'Contact Text': 'contact text here',
  'Contact Type': 'Other'}]

嵌套列表理解在IMHO中是一种糟糕的做法。列表理解必须保持简单(可读性计数)。