Reputation: 99
I have a dictionary of lists of numbers, e.g.:
tDict = {1:[400,200,400,100,0],2:[100,200,300,400,400],3:[200,200,200,100,100]}
I am not allowed to have duplicate values in the lists so my strategy is to iterate through and replace duplicate values with incremented values. This would produce:
{1:[400,200,401,100,0],2:[100,200,300,400,401],3:[200,201,202,100,101]
I have tried multiple combinations of counters etc to achieve this:
for k,v in tdict.items():
for x in range(len(v)):
for y in range(len(v):
if v[x]==v[y] and y!0
v[y]+=1
etc. (Im pretty new to python as you can probably guess). Any help would be greatly appreciated.
Upvotes: 1
Views: 84
Reputation: 78546
Here's one way to do it with itertools.count
building a new dict from each of the lists and then incrementing the count object when a new instance of an integer is found. The current count is then added to the number:
from itertools import count
for k, v in tDict.items():
d = {k: count() for k in v}
tDict[k] = [x+next(d[x]) for x in v]
print tDict
# {1: [400, 200, 401, 100, 0],
# 2: [100, 200, 300, 400, 401],
# 3: [200, 201, 202, 100, 101]}
Upvotes: 3
Reputation: 177
Try This:
for k, v in tDict.iteritems():
new_list = []
for item in v:
while item in new_list:
item += 1
new_list.append(item)
tDict[k] = new_list
Upvotes: 0