更新词典列表中的列表值

dru*_*rum 3 python lambda dictionary

我有一个字典列表(很像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)
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

编辑:'a'和'b'不是唯一的关键.这些仅用于演示目的.

tao*_*k A 7

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

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

for d in lst:
    d['a'] *= 100
Run Code Online (Sandbox Code Playgroud)

使用列表推导会给你速度,但它会创建一个新的列表和新的dicts,如果你不想改变你的列表,这是有用的,这里是

new_lst = [{**d, 'a': d['a']*100} for d in lst]
Run Code Online (Sandbox Code Playgroud)

python 2.X中我们不能使用{**d}所以我custom_update基于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]
Run Code Online (Sandbox Code Playgroud)

如果列表中的每个项目都要更新其他键

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
Run Code Online (Sandbox Code Playgroud)

使用列表理解

[{**d, keys[index]: d[keys[index]] * 100} for index, d in enumerate(lst)]
Run Code Online (Sandbox Code Playgroud)

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)]
Run Code Online (Sandbox Code Playgroud)


g.d*_*d.c 5

您可以在理解范围内的更好位置使用内联条件(三元组):

>>> d = [{'a': 2, 'b': 2}, {'a': 1, 'b': 2}, {'a': 1, 'b': 2}, {'a': 1, 'b': 2}]
>>> d2 = [{k: v * 100 if k == 'a' else v for k, v in i.items()} for i in d]
>>> d2
[{'a': 200, 'b': 2}, {'a': 100, 'b': 2}, {'a': 100, 'b': 2}, {'a': 100, 'b': 2}]
Run Code Online (Sandbox Code Playgroud)