Search code examples
pythonstringdictionarystring-length

Create dictionary with length of string as key and string as value


I have a list with random strings, as the one below:

strings =  ["zone", "abigail", "theta", "form", "libe", "zas"] 

What I want is a dictionary with len of those strings (non unique, linear as they are in the list) as keys, and strings as values. Seems banal, but I am trying to do this in one line, find a nicer way to write it.

I tried this:

dict_of_len = {len(element):element for element in strings} 

but somehow I get this as an output:

{4: 'libe', 7: 'abigail', 5: 'theta', 3: 'zas'}

len(dict_of_len) equals 4. What am I doing wrong?

What I would like to have is this:

{4: 'zone', 7: 'abigail', 5: 'theta', 4: 'form', 4: 'libe', 3: 'zas'}

Solution

  • dict keys must be unique, a better alternative solution to your problem is storing lengths as keys (as you did before) and lists of strings with that length as values, you can do this using itertools.groupby (which requires that the data be sorted by the criteria it will be grouped by):

    strings =  ["zone", "abigail", "theta", "form", "libe", "zas"] 
    
    from itertools import groupby
    
    dict_of_len = {k: list(g) for k, g in groupby(sorted(strings, key = len), len)}
    
    print(dict_of_len)
    

    Output:

    {3: ['zas'], 4: ['zone', 'form', 'libe'], 5: ['theta'], 7:['abigail']}