简体   繁体   English

在字典列表中查找键值,然后替换其他值

[英]Find key value in list of dictionaries, and then replace the other values

I'm using Python and a JSON file containing a list of dictionaries like so:我正在使用 Python 和 JSON 文件,其中包含如下字典列表:

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

And I have an incoming dictionary with the same format:我有一个格式相同的传入字典:

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

The incoming dictionary can have one thing in common, and that's the name key, if the value for the 'name' key hasn't been seen, I add it the json file, if it has, I update the values for the id and status keys in the json file.传入的字典可能有一个共同点,那就是name键,如果没有看到“名称”键的值,我将它添加到json文件中,如果有,我更新idjson文件中的status键。 I'm having trouble updating the list of dictionaries in the json file.我在更新json文件中的字典列表时遇到问题。

Taking the examples I gave above, the resulting json file should look like this:以我上面给出的示例为例,生成的json文件应如下所示:

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

I can manage to find the dictionary I want to change with the following:我可以通过以下方式找到我想要更改的字典:

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

After this, I'm stuck trying to figure out how to then update the specific dictionary in the json file.在此之后,我一直试图弄清楚如何更新json文件中的特定字典。 Any ideas?有任何想法吗? Thank you.谢谢你。

Here is how:方法如下:

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)


You can also use a function:您还可以使用 function:

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)
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)

Here's a function that does so, maybe not as elegantly as other answers:这是一个 function 这样做,可能不像其他答案那样优雅:

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

Full example:完整示例:

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

Result:结果:

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

You can do this while avoiding the global keyword as well, but I thought this seemed alright for modifying an existing structure in place.您也可以在避免使用global关键字的同时执行此操作,但我认为这对于修改现有结构似乎没问题。

Maybe this can help you, and if you found another short solution please let me know.也许这可以帮助您,如果您找到另一个简短的解决方案,请告诉我。 I make an iteration for the list of dictionary, and add a conditional to change the value of key id and status.我对字典列表进行了迭代,并添加了一个条件来更改键 id 和状态的值。 Another way is we can use filter and map, to have a short code instead.另一种方法是我们可以使用过滤器和 map 来代替短代码。

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"]

暂无
暂无

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

相关问题 对于一个键值,计算字典列表中其他键值的出现次数 - For one key value count the occurrences of other key values in list of dictionaries 用列表列表中的值替换字典(列表中)的值 - Replace values of dictionaries (in a list) with a value in list of lists 用相应的值替换字典列表中的空值 - Replace empty values in list of dictionaries by corresponding value 如果两个字典的值/关键字对匹配,则用另一个字典的值替换列表对象字典的值 - Replace list object dictionary values with values of another dictionary, if value/key pairs of two dictionaries match 根据其他列表值查找替换列表值 - Find an replace list value based on other list values 如果两个其他键值对匹配,则为字典列表的Python和值 - Python sum values of list of dictionaries if two other key value pairs match 获取与字典中其他键值关联的键值 Python - get a value of a key associated with other key's values in dictionaries Python 如何根据另一个字典替换列表字典中键的值? - How to replace a value for a key in dictionaries of a list based on another dictionary? 通过基于另一个键的值组合on键的值来获取字典列表 - get list of dictionaries by combining values of on key based on value of another key 如何遍历两个列表字典,以将唯一键值附加到一个列表字典,并通过共享重复值条目继续执行其他字典? - How to loop through two list dictionaries to append unique key values to one list dict and continue through other with shared repeating value entries?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM