0

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'}
2
  • 2
    dict key should be unique Commented Sep 3, 2019 at 22:15
  • That actually explains everything, thank you very much Commented Sep 3, 2019 at 22:19

3 Answers 3

4

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']}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

i use this:

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

1 Comment

That would make a dictionary where the keys are strings and the values are lengths, which isn't what the OP asked for

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.