gpt4 book ai didi

python - 更新字典列表中的列表值

转载 作者:太空宇宙 更新时间:2023-11-03 12:22:58 24 4
gpt4 key购买 nike

我有一个字典列表(很像 JSON)。我想对列表中每个字典中的键应用一个函数。

>> d = [{'a': 2, 'b': 2}, {'a': 1, 'b': 2}, {'a': 1, 'b': 2}, {'a': 1, 'b': 2}]

# Desired value
[{'a': 200, 'b': 2}, {'a': 100, 'b': 2}, {'a': 100, 'b': 2}, {'a': 100, 'b': 2}]

# If I do this, I can only get the changed key
>> map(lambda x: {k: v * 100 for k, v in x.iteritems() if k == 'a'}, d)
[{'a': 200}, {'a': 100}, {'a': 100}, {'a': 100}]

# I try to add the non-modified key-values but get an error
>> map(lambda x: {k: v * 100 for k, v in x.iteritems() if k == 'a' else k:v}, d)

SyntaxError: invalid syntax
File "<stdin>", line 1
map(lambda x: {k: v * 100 for k, v in x.iteritems() if k == 'a' else k:v}, d)

我怎样才能做到这一点?

编辑:“a”和“b”不是唯一的键。选择这些仅用于演示目的。

最佳答案

遍历列表并更新所需的字典项,

lst = [{'a': 2, 'b': 2}, {'a': 1, 'b': 2}, {'a': 1, 'b': 2}, {'a': 1, 'b': 2}]

for d in lst:
d['a'] *= 100

使用列表理解会提高速度,但它会创建一个新列表和 n 个新字典,如果你不想改变你的列表,这很有用,就在这里

new_lst = [{**d, 'a': d['a']*100} for d in lst]

python 2.X 中我们不能使用 {**d} 所以我基于 update 构建了 custom_update 方法和代码将是

def custom_update(d):
new_dict = dict(d)
new_dict.update({'a':d['a']*100})
return new_dict

[custom_update(d) for d in lst]

如果您要为列表中的每个项目更新不同的键

keys = ['a', 'b', 'a', 'b'] # keys[0] correspond to lst[0] and keys[0] correspond to lst[0], ...

for index, d in enumerate(lst):
key = keys[index]
d[key] *= 100

使用列表理解

[{**d, keys[index]: d[keys[index]] * 100} for index, d in enumerate(lst)]

python 2.x 中,列表理解将是

def custom_update(d, key):
new_dict = dict(d)
new_dict.update({key: d[key]*100})
return new_dict

[custom_update(d, keys[index]) for index, d in enumerate(lst)]

关于python - 更新字典列表中的列表值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48105486/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com