在字典列表中替换字典的特定项目?

时间:2019-08-20 12:57:18

标签: python

说我有以下字典列表:

dicts = [
    {'name': "Tom", 'age': 20, 'height': 1.8},
    {'name': "Isa", 'age': 31, 'height': 1.5},
    ... ]

我想用给定的值替换给定人的年龄。

def replace_age(person, age):
    dicts[?]['age'] = age

replace_age("Tom", 45)

假设name是唯一的,最优雅的方法是什么?


在黄金世界中:dicts[name=person]['age'] = age


不是Find the index of a dict within a list, by matching the dict's value的重复项:我想更改值,而不是获取索引。而且汤姆是个很普通的名字。

3 个答案:

答案 0 :(得分:3)

这是一个变体:

def replace_age(person, age):
    try:
        dct = next(item for item in dicts if item["name"] == person)
    except StopIteration:
        # person not found
        # here you could print a message or raise an error...
        return
    dct["age"] = age

这仅在名称唯一的情况下有效。如果它们不只是第一次出现,将会被替换。

答案 1 :(得分:1)

这是我的版本

dictionaries = [
    {'name': "Tom", 'age': 20, 'height': 1.8},
    {'name': "Isa", 'age': 31, 'height': 1.5}
    ]

def change_dict_person_age(dictionaries, person, age):
    for dictionary in dictionaries:
        if dictionary['name'] == person:
            dictionary['age'] = age
            # Uncomment the following line if you want to stop at the 1st
            # match. Leave it as is if you want to modify all occurrences.
            #break

change_dict_person_age(dictionaries, "Tom", 40)
print(dictionaries)
#[{'name': 'Tom', 'age': 40, 'height': 1.8}, {'name': 'Isa', 'age': 31, 'height': 1.5}]

我还为更广泛的用户编写了一个更通用的版本:

dictionaries = [
    {'name': "Tom", 'age': 20, 'height': 1.8},
    {'name': "Isa", 'age': 31, 'height': 1.5}
    ]

def change_dict(dictionaries, key_to_check, value_to_match, key_to_change, value_to_change):
    for dictionary in dictionaries:
        if dictionary[key_to_check] == value_to_match:
            dictionary[key_to_change] = value_to_change
            # Uncomment the following line if you want to stop at the 1st
            # match. Leave it as is if you want to modify all occurrences.
            #break

change_dict(dictionaries, "name", "Tom", "age", 50)
print(dictionaries)
#[{'name': 'Tom', 'age': 50, 'height': 1.8}, {'name': 'Isa', 'age': 31, 'height': 1.5}]

答案 2 :(得分:1)

由于name是唯一的,因此您可以更改数据结构,以保留数据以有效地完成任务:

efficient_dict = {e['name']: {'age' : e.get('age'), 'height': e.get('height')} for e in dicts}

def replace_age(person, age):
    if person in efficient_dict:
        efficient_dict[person]['age'] = age