Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rename duplicates in list of dictionaries by appending progressive numbers at end

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}]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading