Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  { 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']}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading