I have a list that looks like this
[
{'name': 'a', 'value': 'x'},
{'name': 'a', 'value': 'x'},
{'name': 'a', 'value': 'x'},
{'name': 'b', 'value': 'x'},
{'name': 'b', 'value': 'x'},
{'name': 'c', 'value': 'x'}
]
I want to convert it into a dictionary that looks like this
{
'a-0': 'x',
'a-1': 'x',
'a-2': 'x',
'b-0': 'x',
'b-1': 'x',
'c': 'x'
}
So for any duplicated name I want to append an index to the end of all instances, but if the name isn't duplicated than it should just be left.
I have written a function to do this but I don't think it is very efficient or generally pleasant.
def transform(mylist):
names = [x['name'] for x in mylist]
duplicates = {x: 0 for x in names if names.count(x) > 1}
out = {}
for row in mylist:
key = row['name']
value = row['value']
if key in duplicates:
newkey = "{key}-{index}".format(key=key, index=duplicates[key])
duplicates[key] = duplicates[key] + 1
else:
newkey = key
out[newkey] = value
return out
Is there a better way to do this?