Home > Blockchain >  change each keys of a dictionary based on length of each values
change each keys of a dictionary based on length of each values

Time:06-23

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.

CodePudding user response:

Use a dict comprehension which is very pythonic:

dict_ = { 1:['A', 'B', 'C', 'D', 'E'] , 2:['B', 'C', 'E', 'AD'] , 3:['E', 'AD', 'BC'] , 4:['BC', 'EAD'] , 5:['BCEAD'] }
dict2 = {len(v) : v for k, v in dict_.items()}
>>> {5: ['A', 'B', 'C', 'D', 'E'], 4: ['B', 'C', 'E', 'AD'], 3: ['E', 'AD', 'BC'], 2: ['BC', 'EAD'], 1: ['BCEAD']}

CodePudding user response:

Try this:


dict_old = {1: ['A', 'B', 'C', 'D', 'E'], 2: ['B', 'C', 'E', 'AD'], 3: ['E', 'AD', 'BC'], 4: ['BC', 'EAD'], 5: ['BCEAD']}
dict_new = {}
for k, v in dict_old.items():
    dict_new[len(v)] = v
print(dict_new)

CodePudding user response:

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']}

CodePudding user response:

you could do it by dict comprehension:

>>> dict_ = { 1:['A', 'B', 'C', 'D', 'E'] , 2:['B', 'C', 'E', 'AD'] , 3:['E', 'AD', 'BC'] , 4:['BC', 'EAD'] , 5:['BCEAD'] }
>>> dict2 = {len(v) : v for _, v in dict_.items()}
{5: ['A', 'B', 'C', 'D', 'E'], 4: ['B', 'C', 'E', 'AD'], 3: ['E', 'AD', 'BC'], 2: ['BC', 'EAD'], 1: ['BCEAD']}

or you could do that with a map function:

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

>>> new_dict = dict(map(lambda x:(len(x[1]),x[1]),dict_))
>>> new_dict
{5: ['A', 'B', 'C', 'D', 'E'],
 4: ['B', 'C', 'E', 'AD'],
 3: ['E', 'AD', 'BC'],
 2: ['BC', 'EAD'],
 1: ['BCEAD']}
  • Related