[Solved] auto increment by group in list object python


I am also not sure if I see what you mean. Furthermore if I follow your example, should this not be sita and lia with a 0 and not 1? indra and fajar start with 0, too.

Anyhow. This might help:

d = [{'id': '1', 'nama': 'fajar'}, {'id': '2', 'nama': 'fajar'}, {'id': '3', 'nama': 'fajar'}, {'id': '4', 'nama': 'fajar'}, {'id': '5', 'nama': 'sita'}, {'id': '6', 'nama': 'lia'}, {'id': '7', 'nama': 'indra'}, {'id': '8', 'nama': 'indra'}, {'id': '9', 'nama': 'indra'}, {'id': '10', 'nama': 'indra'}]
c = {}
for i in d:
    if not i["nama"] in c:
        c[i["nama"]] = 0
    c[i["nama"]] += 1
    i["nama"] += str(c[i["nama"]] - 1)

gives

[{'id': '1', 'nama': 'fajar0'},
 {'id': '2', 'nama': 'fajar1'},
 {'id': '3', 'nama': 'fajar2'},
 {'id': '4', 'nama': 'fajar3'},
 {'id': '5', 'nama': 'sita0'},
 {'id': '6', 'nama': 'lia0'},
 {'id': '7', 'nama': 'indra0'},
 {'id': '8', 'nama': 'indra1'},
 {'id': '9', 'nama': 'indra2'},
 {'id': '10', 'nama': 'indra3'}]

2

solved auto increment by group in list object python