更新字典数组中的字典值

时间:2015-03-31 02:20:12

标签: python python-2.7 dictionary

我在Python 2.7中有这个字典数组

[{'t': 1, 'l': 'cd', 'e': 'extra'}, {'t': 2, 'l': 'ab'}, {'t': 3, 'l': 'abc'}, {'t': 4, 'l': 'ab'}]

如何更新它以在重复的'l'值上附加一个计数器,以便结果如下所示?

[{'t': 1, 'l': 'cd', 'e': 'extra'}, {'t': 2, 'l': 'ab_1'}, {'t': 3, 'l': 'abc'}, {'t': 4, 'l': 'ab_2'}]

由于

3 个答案:

答案 0 :(得分:0)

取决于您希望如何识别要更新的内容,

a[-1]['l'] += '_2'

可能就够了。但如果那不是你想要的,你最好更多更具体地说明你打算如何准确标记要更新的内容! - )

答案 1 :(得分:0)

一个相当简单的解决方案是首先根据' l'的值将字典列表转换为列表字典。然后,您可以将其转换回原始形状,将后缀添加到多列表元素。

答案 2 :(得分:0)

你可以这样做:

a_list = [{'t': 1, 'l': 'cd'}, {'t': 2, 'l': 'ab'}, {'t': 3, 'l': 'abc'}, {'t': 4, 'l': 'ab'}]

# keep 'l' values, so that we can calculate how many of them we have
list_of_values = []

out_list = []

# iterate through each dict in the input list 
# to create out_list with appended counter on duplicate 'l' values
for d in a_list:
    l_value, t_value = d['l'], d['t']         

    list_of_values.append(l_value)

    l_count = list_of_values.count(l_value)

    if l_count > 1:
    # add new dict to out_list, so that 'l' values contain number 
    # of times they appear in a_list. t value is same as it was.            
    #out_list.append({'t': t_value, 'l':"{}_{}".format(l_value, l_count)})
        out_list.append({'t': t_value, 'l':"{}_{}".format(l_value, l_count)})
    else:
        out_list.append(d)


print(out_list)    

结果是:

[{'l': 'cd', 't': 1}, {'l': 'ab', 't': 2}, {'l': 'abc', 't': 3}, {'l': 'ab_2', 't': 4}]