Home > Enterprise >  How to count the length of the words of a list and represent the count , words as key value pairs in
How to count the length of the words of a list and represent the count , words as key value pairs in

Time:01-18

I have a dictionary:

names = ['arun', 'vinod', 'karthik', 'sita', 'ramu', 'arvind', 'abinav', 'malu', 'prakash']

I want the result as:

{4: ['arun', 'sita', 'ramu', 'malu'],  5: ['vinod'], 6: ['arvind', 'abinav'], 7: ['karthik', 'prakash']}

I tried using:

names = ['arun', 'vinod', 'karthik', 'sita', 'ramu', 'arvind', 'abinav', 'malu', 'prakash']

f = {} 


    
for str in names:
    if str in f:
        f[str]  = len(str)
    else:
        f[str] = len(str)
            
            


new_dict = {}
for key, value in f.items():
   if value in new_dict:
       new_dict[value].append(key)
   else:
       new_dict[value]=[key]
        
print(new_dict)

I got the solution as:

{4: ['arun', 'sita', 'ramu', 'malu'], 5: ['vinod'], 7: ['karthik', 'prakash'], 6: ['arvind', 'abinav']}

Any more improvements or quicker method on this?

CodePudding user response:

Defaultdict is suited really well for a task like this.

Code example:

from collections import defaultdict

names = ['arun', 'vinod', 'karthik', 'sita', 'ramu', 'arvind', 'abinav', 'malu', 'prakash']
result = defaultdict(list)
for name in names:
    result[len(name)].append(name)

normal_dict = dict(result)
print(normal_dict)

Output:

{4: ['arun', 'sita', 'ramu', 'malu'], 5: ['vinod'], 7: ['karthik', 'prakash'], 6: ['arvind', 'abinav']}

CodePudding user response:

you can write like this:

dict={}
for i in names:
    if len(i) in dict.keys():
        dict[len(i)].append(i)
    else:
        dict[len(i)]=[i] 

Output:

{4: ['arun', 'sita', 'ramu', 'malu'],
 5: ['vinod'],
 7: ['karthik', 'prakash'],
 6: ['arvind', 'abinav']}

CodePudding user response:

You can also write:


names = ['arun', 'vinod', 'karthik', 'sita', 'ramu', 'arvind', 'abinav', 'malu', 'prakash']
f = {}
for name,l in list(map(lambda name: (name, len(name)), names)):
    f[l] = f.get(l, [])   [name]

Output

{4: ['arun', 'sita', 'ramu', 'malu'],
 5: ['vinod'],
 7: ['karthik', 'prakash'],
 6: ['arvind', 'abinav']}

  •  Tags:  
  • Related