Search code examples
pythonfunctiondictionaryon-duplicate-key

How to add prefix/suffix on a repeatable dictionary key in Python


Could you please suggest is there any way to keep all the repeatable (duplicate) keys by adding prefix or suffix. In the below example, the address key is duplicated 3 times. It may vary (1 to 3 times). I want to get the output as in the expected output with adding a suffix to make the key unique. Currently the update function is overwriting the key value.

list = ['name:John','age:25','Address:Chicago','Address:Phoenix','Address:Washington','email:[email protected]']
dic = {}
for i in list:
    j=i.split(':')
    dic.update({j[0]:j[1]})
print(dic)

Current output: {'name': 'John', 'age': '25', 'Address': 'Washington', 'email': '[email protected]'}

Expected output: {'name': 'John', 'age': '25', 'Address1': 'Chicago', 'Address2': 'Phoenix', 'Address3': 'Washington', 'email': '[email protected]'}

Tried the below:

list = ['name:John','age:25','Address:Chicago','Address:Phoenix','Address:Washington','email:[email protected]']
dic = {}
for i in list:
    j=i.split(':')
    dic.update({j[0]:j[1]})
print(dic)

Expected output: {'name': 'John', 'age': '25', 'Address1': 'Chicago', 'Address2': 'Phoenix', 'Address3': 'Washington', 'email': '[email protected]'}


Solution

  • You can use something like this:

    list_ = ['name:John','age:25','Address:Chicago','Address:Phoenix','Address:Washington','email:[email protected]']
    
    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]
    

    Output:

    {'name': 'John',
     'age': '25',
     'Address': 'Chicago',
     'Address1': 'Phoenix',
     'Address2': 'Washington',
     'email': '[email protected]'}
    

    PS. don't use the python keyword list to name your variables as it overrides the type list