【问题标题】:Update list in dictionary in a list of dictionaries更新字典列表中的字典列表
【发布时间】:2021-11-13 04:50:14
【问题描述】:
list = [{'id': 1, 'tags': ['tag1', 'tag2']}, {'id': 2, 'tags': ['tag5', 'tag7']}]

id = 1
tag = 'tag10'

"""
#for i element in list, if list[i]['id'] == 1, update list[i][tags].append(tag)
else:
    dic = {'id': id, 'tags': [tag]}
    list.append(dic)
"""

我需要检查字典列表中是否已经存在 id = 1 的字典,如果存在,将 tag 变量附加到他的 tags 列表中,否则创建一个新的 dic 并将其附加到列表中。

脚本应将列表更新为:

list = [{'id': 1, 'tags': ['tag1', 'tag2', 'tag10']}, {'id': 2, 'tags': ['tag5', 'tag7']}]

【问题讨论】:

    标签: python


    【解决方案1】:

    遍历列表中的字典。在每次迭代中检查是否有一个名为“id”的键。如果有,请获取同一 dict 的 'tags' 键的值并附加您的标签。

    my_list = [{'id': 1, 'tags': ['tag1', 'tag2']}, {'id': 2, 'tags': ['tag5', 'tag7']}]
    
    id = 1
    tag = 'tag10'
    
    for a_dict in my_list:
        if a_dict.get('id', 0) == id:
            a_dict['tags'].append(tag)
    

    如果您知道这只会发生在您的一个 dicts 上,您可以在代码上添加 break,这样它就不会遍历其余的 em。

    使用未分配的列表理解单线可以实现相同的行为:

    [a_dict['tags'].append(tag) for a_dict in my_list if a_dict.get('id', 0) == id]
    

    【讨论】:

    • 为什么你使用 a_dict.get('id', 0) 而不是 a_dict['id']?
    • @Hyperion 因为其中一个字典可能完全缺少 id 键。 get 将返回 0 并且检查将失败且不会引发错误
    • 这被认为是bad style。您不应该使用列表推导来解决它们的副作用。您正在创建[None] * num_dicts_with_id_of_1。如果num_dicts_with_id_of_1 最终变大,那么在后台你正在创建一个大对象,然后必须对其进行垃圾收集。
    【解决方案2】:

    这应该做你想做的事

    my_list = [{'id': 1, 'tags': ['tag1', 'tag2']}, {'id': 2, 'tags': ['tag5', 'tag7']}]
    
    target_id = 1
    tag = 'tag10'
    
    for dictionary in my_list:
         current_id = dictionary[id]
         if current_id == target_id:
              dictionary['tags'] = tag
         else:
              my_list.append({'id': target_id, tags: [tag]})
    

    【讨论】:

      【解决方案3】:
      lst = [{'id': 1, 'tags': ['tag1', 'tag2']}, {'id': 2, 'tags': ['tag5', 'tag7']}]
      id_ = 1
      tag = 'tag10'
      
      # iterate through the list; each item in list is a dict
      for  item in lst:
          # check if reqd id_ is present in the dict
          if item['id'] == id_:
            # check if tags key is present in the dict
            # if yes append to the list
            if 'tags' in item.keys():
              item['tags'].append(tag)
          else:
            item['tags'] = tag
      
      print lst
      

      【讨论】:

      • 虽然此代码可以回答问题,但提供有关它为什么和/或如何回答问题的额外上下文将显着提高其长期价值。请edit你的答案添加一些解释。
      • @CodeMouse92 因为代码很简单,我觉得不需要添加任何东西。我现在已经添加了 cmets。
      猜你喜欢
      • 2017-02-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 2019-02-21
      • 2018-02-06
      • 1970-01-01
      相关资源
      最近更新 更多