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

Question:

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'}
Asked By: Luigi

||

Answers:

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']}
Answered By: DjaouadNM

As an alternative to the groupby solution, which requires pre-sorting, you can use a defaultdict or use setdefault to concisely accumulate a list of values:

from collections import defaultdict
dict_of_len = defaultdict(list)
for str in strings:
    dict_of_len[len(str)].append(str)

Or, using the older idiom:

dict_of_len = {}
for str in strings:
    dict_of_len.setdefault(len(str), []).append(str)

But there’s nothing wrong with the groupby solution as long as you don’t mind sorting.

Answered By: Peter DeGlopper

i use this:

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