代码之家  ›  专栏  ›  技术社区  ›  Rob

在字典中更新字典中的值

  •  0
  • Rob  · 技术社区  · 10 年前

    如果我有这样的联系人字典列表:

    {'name': 'Rob', 'phoneNumbers': [{'phone': '123-3214', 'type': 'home'}, {'phone': '456-3216', 'type': 'work'}]}
    

    我如何更新这本字典,以删除联系人字典列表中电话号码的破折号?

    2 回复  |  直到 10 年前
        1
  •  4
  •   Martijn Pieters    10 年前

    您可以只嵌套循环:

    for contact_dict in list_of_dicts:
        for phone_dict in contact_dict['phoneNumbers']:
            phone_dict['phone'] = phone_dict['phone'].replace('-', '')
    

    这将改变现有的值。

    或者,您可以创建一个结构的全新副本,并进行以下更改:

    [dict(contact, phoneNumbers=[
        dict(phone_dict, phone=phone_dict['phone'].replace('-', '')) 
        for phone_dict in contact['phoneNumbers']])
     for contact in list_of_dicts]
    

    这将创建一个半浅副本;只有 phoneNumbers 键被显式复制,但任何其他可变值都只被新字典引用。

    演示:

    >>> list_of_dicts = [{'name': 'Rob', 'phoneNumbers': [{'phone': '123-3214', 'type': 'home'}, {'phone': '456-3216', 'type': 'work'}]}]
    >>> [dict(contact, phoneNumbers=[
    ...     dict(phone_dict, phone=phone_dict['phone'].replace('-', ''))
    ...     for phone_dict in contact['phoneNumbers']])
    ...  for contact in list_of_dicts]
    [{'phoneNumbers': [{'phone': '1233214', 'type': 'home'}, {'phone': '4563216', 'type': 'work'}], 'name': 'Rob'}]
    >>> for contact_dict in list_of_dicts:
    ...     for phone_dict in contact_dict['phoneNumbers']:
    ...         phone_dict['phone'] = phone_dict['phone'].replace('-', '')
    ...
    >>> list_of_dicts
    [{'phoneNumbers': [{'phone': '1233214', 'type': 'home'}, {'phone': '4563216', 'type': 'work'}], 'name': 'Rob'}]
    
        2
  •  1
  •   Padraic Cunningham    10 年前

    只是 str.replace 这个 -

    d ={'name': "Rob", 'phoneNumbers': [{'phone': '123-3214', 'type': 'home'}, {'phone': '456-3216', 'type': 'work'}]}
    
    for dct in d["phoneNumbers"]:
        dct['phone'] = dct['phone'].replace("-","",1)
    

    这给了你:

    {'phoneNumbers': [{'phone': '1233214', 'type': 'home'}, {'phone': '4563216', 'type': 'work'}], 'name': 'Rob'}