【发布时间】:2013-08-19 11:29:07
【问题描述】:
我正在尝试基于现有字典创建一个新字典:在这个新字典中,我想在每个值的末尾附加一个递增的整数。我的 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'}*
当我想得到时
*{40: 'b_1', 10: 'a_2', 50: 'c_1', 20: 'a_1', 60: 'c_2', 30: 'b_2'}.*
字典顺序并不重要。 谢谢您的帮助。 亲切的问候。 伊沃
【问题讨论】:
-
附带说明,不要调用您的字典
dict,否则您将永远无法在脚本的其余部分再次调用dict构造函数。 -
感谢您指出这一点。亲切的问候。伊沃
标签: python dictionary