加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 12:34:54 所属栏目:Python 来源:网络整理
导读:我有一个字典列表(很像 JSON).我想将一个函数应用于列表的每个字典中的一个键. d = [{'a': 2,'b': 2},{'a': 1,'b': 2}]# Desired value[{'a': 200,{'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
我有一个字典列表(很像 JSON).我想将一个函数应用于列表的每个字典中的一个键.

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

# Desired value
[{'a': 200,{'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}]

# 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,d)

我怎样才能做到这一点?

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

解决方法

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

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

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

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

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

在python 2.X中我们不能使用{** d}所以我根据更新方法构建了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)]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读