首页> 疑难解答

编辑词典列表中的值?

withpy 2021-06-19

简介my_dicts = [{'key1':'value1','key2':'value2'},{'key1':'value1','key2':'value2'},{'key1':'value1','key2 ':'value2'}]最多的是什么......

my_dicts = [ 
    { 'key1' : 'value1',
      'key2' : 'value2' },

    { 'key1' : 'value1',  
      'key2' : 'value2' },

    { 'key1' : 'value1',  
      'key2' : 'value2' }]

用'value3'替换'value2'的所有实例的最有效方法是什么?

36
投票

我没有做任何时间,但你可能不会比这更好

for d in my_dicts:
    d.update((k, "value3") for k, v in d.iteritems() if v == "value2")

Python3的更新

for d in my_dicts:
    d.update((k, "value3") for k, v in d.items() if v == "value2")

2
投票

这是一个非常通用的答案,旨在处理大型词典中多个值的多次出现。处理更简单的更具体的案例和/或使用小词典(如您的示例)可以更快地完成。

from collections import defaultdict

my_dicts = [
    { 'key1' : 'value1',
      'key2' : 'value2' },

    { 'key1' : 'value1',
      'key2' : 'value2',
      'key3' : 'value2'  }, # dup added for testing

    { 'key1' : 'value1',
      'key2' : 'value2' }]

def reverse(dct):
    """ Create dictionary mapping each value to list of one or more keys """
    ret = defaultdict(list)
    for key,val in dct.iteritems():
        ret[val].append(key)
    return ret

def replace_values(dicts, replacments):
    """ Replace values in each dict in dicts """
    for dct in dicts:
        revdict = reverse(dct)
        for oldval,newval in replacments.iteritems():
            for key in revdict.get(oldval, []):
                dct[key] = newval

replace_values(my_dicts, {'value2':'value3'})
print my_dicts
# [{'key2': 'value3', 'key1': 'value1'},
#  {'key3': 'value3', 'key2': 'value3', 'key1': 'value1'},
#  {'key2': 'value3', 'key1': 'value1'}]

-1
投票

编辑:

要么。

for item in my_dicts:
   item['key2'] = 'value3'

相关文章