如何在 Python 中的可重复字典键上添加前缀/后缀

Sri*_*Sri 5 python dictionary function on-duplicate-key

您能否建议是否有任何方法可以通过添加前缀或后缀来保留所有可重复(重复)的键。在下面的示例中,地址键重复 3 次。它可能会有所不同(1 到 3 次)。我想获得预期输出中的输出,并添加后缀以使密钥唯一。目前更新功能正在覆盖键值。

list = ['name:John','age:25','Address:Chicago','Address:Phoenix','Address:Washington','email:John@email.com']
dic = {}
for i in list:
    j=i.split(':')
    dic.update({j[0]:j[1]})
print(dic)
Run Code Online (Sandbox Code Playgroud)

当前输出:{'name':'John','age':'25','Address':'Washington','email':'John@email.com'}

预期输出:{'name':'John','age':'25','Address1':'芝加哥','Address2':'Phoenix','Address3':'华盛顿','email':'John @email.com'}

尝试了以下方法:

list = ['name:John','age:25','Address:Chicago','Address:Phoenix','Address:Washington','email:John@email.com']
dic = {}
for i in list:
    j=i.split(':')
    dic.update({j[0]:j[1]})
print(dic)
Run Code Online (Sandbox Code Playgroud)

预期输出:{'name':'John','age':'25','Address1':'芝加哥','Address2':'Phoenix','Address3':'华盛顿','email':'John @email.com'}

小智 1

你可以使用这样的东西:

list_ = ['name:John','age:25','Address:Chicago','Address:Phoenix','Address:Washington','email:John@email.com']

dic = {}
for i in list_:
    j = i.split(':')
    key_ = j[0]
    count = 0 # counts the number of duplicates
    while key_ in dic:
        count += 1
        key_ = j[0] + str(count)
    dic[key_] = j[1]
Run Code Online (Sandbox Code Playgroud)

输出:

{'name': 'John',
 'age': '25',
 'Address': 'Chicago',
 'Address1': 'Phoenix',
 'Address2': 'Washington',
 'email': 'John@email.com'}
Run Code Online (Sandbox Code Playgroud)

附言。不要使用 python 关键字list来命名变量,因为它会覆盖类型list