change each keys of a dictionary based on length of each values

I have a dictionary like this:

{ 1:['A', 'B', 'C', 'D', 'E'] , 2:['B', 'C', 'E', 'AD'] , 3:['E', 'AD', 'BC'] , 4:['BC', 'EAD'] , 5:['BCEAD'] }

is there a way to set length of each value of dictionary as its key ?

I mean, I want to have this dictionary :

  { 5:['A', 'B', 'C', 'D', 'E'] , 4:['B', 'C', 'E', 'AD'] , 3:['E', 'AD', 'BC'] , 2:['BC','EAD'] , 1:['BCEAD'] }

please help me to solve this problem.
thanks.

>Solution :

You can traverse all values of your original dictionary with values() and list() function:

d = { 1:['A', 'B', 'C', 'D', 'E'] , 2:['B', 'C', 'E', 'AD'] , 3:['E', 'AD', 'BC'] , 4:['BC', 'EAD'] , 5:['BCEAD'] }

newD = {}

for i in list(d.values()):
    newD[len(i)] = i
print(newD)

Output: Note that if you have several values of the same length, the dictionary will only have one key. You can’t have more than 1 key being the same in a dictionary

{5: ['A', 'B', 'C', 'D', 'E'], 4: ['B', 'C', 'E', 'AD'], 3: ['E', 'AD', 'BC'], 2: ['BC', 'EAD'], 1: ['BCEAD']}

Leave a Reply