【问题标题】:Find key value in list of dictionaries, and then replace the other values在字典列表中查找键值,然后替换其他值
【发布时间】:2020-10-21 06:38:03
【问题描述】:

我正在使用 Python 和一个包含字典列表的 JSON 文件,如下所示:

[
  {'name':'person1','id':'123','status':'absent'},
  {'name':'person2','id':'0980','status':'away'},
  {'name':'person3','id':'5235','status':'present'}
]

我有一个格式相同的传入字典:

{'name':'person1','id':'324','status':'present'}

传入的字典可以有一个共同点,那就是name键,如果'name'键的值还没有看到,我将它添加到json文件,如果有,我更新 json 文件中 idstatus 键的值。我在更新 json 文件中的字典列表时遇到问题。

以我上面给出的示例为例,生成的json 文件应如下所示:

[
  {'name':'person1','id':'324','status':'present'},
  {'name':'person2','id':'0980','status':'away'},
  {'name':'person3','id':'5235','status':'present'}
]

我可以通过以下方式找到我想要更改的字典:

dict_to_update = next(item for item in <jsonfilename> if item['name'] == 'desired name')

在此之后,我一直在试图弄清楚如何更新 json 文件中的特定字典。 有任何想法吗?谢谢。

【问题讨论】:

    标签: python json list loops dictionary


    【解决方案1】:

    方法如下:

    with open('file.json', 'r') as r:
        lst = json.load(r)
    
    for i,d in enumerate(lst):
        if d['name'] == dct['name']:
            lst[i] = dct
    
    with open('file.json', 'w') as f:
        json.dump(lst , f)
    


    你也可以使用函数:

    def update(lst):
        for i,d in enumerate(lst):
            if d['name'] == dct['name']:
                lst[i] = dct
        return lst
    
    with open('file.json', 'r') as r:
        lst = update(json.load(r))
    
    with open('file.json', 'w') as f:
        json.dump(lst , f)
    

    【讨论】:

    • 我想 l[i] 应该是 lst[i]?
    【解决方案2】:

    也许这可以帮助您,如果您找到了另一个简短的解决方案,请告诉我。 我对字典列表进行了迭代,并添加了一个条件来更改键 id 和状态的值。 另一种方法是我们可以使用过滤器和映射来代替短代码。

    datas = [{'name': 'person1', 'id': '123', 'status': 'absent'}, {'name': 'person2', 'id': '0980',
                                                        'status': 'away'}, {'name': 'person3', 'id': '5235', 'status': 'present'}]
    newData = {'name':'person1','id':'324','status':'present'}
    for data in datas:
        if data["name"]==newData["name"]:
            data["id"]=newData["id"]
            data["status"]=newData["status"]
    

    【讨论】:

      【解决方案3】:

      这是一个这样做的函数,可能不像其他答案那样优雅:

      def process(new_dict):
          global data  #jsonfilename
          if new_dict['name'] in [d['name'] for d in data]:
              data = [d for d in data if d['name'] != new_dict['name']]
          data.append(new_dict)
          data = sorted(data, key=lambda i: i['name'])
      

      完整示例:

      data = [{'name':'person1','id':'123','status':'absent'},
              {'name':'person2','id':'0980','status':'away'},
              {'name':'person3','id':'5235','status':'present'}]
      
      process({'name':'person1','id':'324','status':'present'})  #an overwritten person
      process({'name':'person4','id':'324','status':'present'})  #a new person
      

      结果:

      [{'name': 'person1', 'id': '324', 'status': 'present'},
       {'name': 'person2', 'id': '0980', 'status': 'away'},
       {'name': 'person3', 'id': '5235', 'status': 'present'},
       {'name': 'person4', 'id': '324', 'status': 'present'}]
      

      您也可以在避免使用 global 关键字的同时做到这一点,但我认为这对于修改现有结构似乎没问题。

      【讨论】:

        【解决方案4】:
        list_of_dict = [
            {"name": "person1", "id": "123", "status": "absent"},
            {"name": "person2", "id": "0980", "status": "away"},
            {"name": "person3", "id": "5235", "status": "present"},
        ]
        
        incoming_dictionary = {"name": "person1", "id": "324", "status": "present"}
        
        for index, dictionary in enumerate(list_of_dict):
            if incoming_dictionary["name"] == dictionary["name"]:
                list_of_dict[
                    index
                ] = incoming_dictionary  # replace the dictionary with the new one
                break
        else:
            # if no match was found then append the incoming dictionary
            list_of_dict.append(incoming_dictionary)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-05-25
          • 2018-03-08
          • 1970-01-01
          • 1970-01-01
          • 2023-02-24
          • 2020-08-26
          • 1970-01-01
          • 2020-07-11
          相关资源
          最近更新 更多