how to Assign indexes to multivalued dictionary and store these indexes in multidimentional list

Viewed 36

I have a multivalued dictionary where per key holds minimum 40-50 values,I want to assign an index to every value by order, means first value of first key should be 0.

my dictionary:

{36: [('037.Acadian_Flycatcher/20.jpg', 36),
  ('037.Acadian_Flycatcher/6.jpg', 36),
  ('037.Acadian_Flycatcher/5.jpg', 36),
  ('037.Acadian_Flycatcher/8.jpg', 36),
               ----------
               ----------
144: [('145.Elegant_Tern/20.jpg', 144),
  ('145.Elegant_Tern/6.jpg', 144),
  ('145.Elegant_Tern/5.jpg', 144),
  ('145.Elegant_Tern/8.jpg', 144),
  ('145.Elegant_Tern/30.jpg', 144),
  -            ---------
               ---------

list i want:

my_list =[
   [0,1,2,3,4,5......], # for values of 1st key
   [55,56,57,........], # for values of second key
   [111,112,113,.....], # for values of third key
   -----------------
   ------------------
]

dictionary sorted alphabetically not numerically.

2 Answers

Suppose you have this dictionary:

dct = {
    1: ["val1", "val2", "val3"],
    2: ["val1", "val2", "val3", "val4"],
    3: ["val1", "val2"],
}

Then:


my_list, cnt = [], 0
for k in sorted(dct):
    my_list.append(list(range(cnt, cnt + len(dct[k]))))
    cnt += len(dct[k])

print(my_list)

Prints:

[[0, 1, 2], 
 [3, 4, 5, 6], 
 [7, 8]]

You may iterate on your dict, and regarding the length of the values, add the corresponding indices

values = {
    1: ['a', 'b', 'c'],
    123: ['A', 'B'],
    12: ['a', 'c'],
    45: ['y', 'u']
}

print(sorted(values, key=lambda x: str(x)))  # [1, 12, 123, 45]

result, count = [], 0
for key in sorted(values, key=lambda x: str(x)):
    l = len(values[key])
    result.append(list(range(count, count + l)))
    count += l

print(result)  # [[0, 1, 2], [3, 4], [5, 6], [7, 8]]
Related