Home > Software design >  Rename duplicates in list of dictionaries by appending progressive numbers at end
Rename duplicates in list of dictionaries by appending progressive numbers at end

Time:03-22

Given a list of dictionaries like this

a_list = [{'name':'jennifer','roll_no':22}, {'name':'kristina','roll_no':26},
{'name':'jennifer','roll_no':18}, {'name':'kristina','roll_no':33}]

How could this be renamed to

a_list = [{'name':'jennifer','roll_no':22}, {'name':'kristina','roll_no':26},
{'name':'jennifer 1','roll_no':18}, {'name':'kristina 1','roll_no':33}]

CodePudding user response:

You want to construct a new list of dictionaries, but whenever a new dictionary is added that has a 'name' value that was already present, you want to use the next available option.

There's different approaches but one would be:

  • loop over all the dictionaries in a_list and add them to a new list
  • before adding them, check some register of used names to see if their name is in there, if not, just add it; if so, get and increase the number associated with it and update the dictionary

So, in code:

a_list = [
    {'name':'jennifer','roll_no':22}, {'name':'kristina','roll_no':26},
    {'name':'jennifer','roll_no':18}, {'name':'kristina','roll_no':33}
]

names = {}
result = []
for d in a_list:
    if (name := d['name']) not in names:
        names[name] = 0
    else:
        names[name]  = 1
        d['name'] = f'{name} {names[name]}'
    result.append(d)

print(result)

Result:

[{'name': 'jennifer', 'roll_no': 22}, {'name': 'kristina', 'roll_no': 26}, {'name': 'jennifer 1', 'roll_no': 18}, {'name': 'kristina 1', 'roll_no': 33}]
  • Related