如何将越来越多的数字附加到字典值?

时间:2013-08-17 00:09:19

标签: python dictionary

我正在尝试基于现有的dict创建一个新的字典:在这个新的dict中,我想在每个值的末尾附加一个递增的整数。我的dict有几个键,但重复价值。

我使用以下代码有一个我想要实现的例子:

list_1 = [10,20,30,40,50,60]
list_2 = ["a","a","b","b","c","c"]

dict = dict(zip(list_1,list_2))

another_dict = {}
counter = 0
for keys in dict.keys():
    if dict[keys] == "a" :
        counter += 1
        another_dict[keys] = "a_" + str(counter)
    if dict[keys] == "b":
        counter += 1
        another_dict[keys] = "b_" + str(counter)
    if dict[keys] == "c":
        counter += 1
        another_dict[keys] = "c_" + str(counter)

print(another_dict)

我得到了这个结果

* {40:'b_1',10:'a_2',50:'c_3',20:'a_4',60:'c_5',30:'b_6'} * < / p>

当我想要

* {40:'b_1',10:'a_2',50:'c_1',20:'a_1',60:'c_2',30:'b_2'}。*

字典顺序并不重要。 谢谢您的帮助。 亲切的问候。 IVO

2 个答案:

答案 0 :(得分:2)

每个不同的值都需要一个不同的计数器。

答案 1 :(得分:1)

这应该可以解决问题:

another_dict = {}
counters = {}
for key,value in dict.items():
    counter = counters.get(value, 0) + 1
    counters[value] = counter
    another_dict[key] = "%s_%d" % (value, counter)

counters会跟踪每个值的计数。如果它没有初始化,则从零开始(感谢字典.get()调用)。

相关问题