Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create dictionary with length of string as key and string as value without import statement?

Can you create a dictionary with length of string as key and string as value without an import statement?

With an import statement it would look like this:

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

Output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

If possible I would like two options, where for one of the options the value is a list of values, and another option where the value is a set of values.

I tried this by myself but I keep getting difficulties when there are multiple values for the same key.

one of my failed attempts

for i in strings:
   dictio = dict()
   set1 = set()
   set1.add(i)
   dictio[len(i)] = set1
print(dictio)

output

{3: {'zas'}}

>Solution :

This would be easier with a defaultdict, but you can do it without any imports.

To use lists as values:

strings =  ["zone", "abigail", "theta", "form", "libe", "zas"] 
dict_of_len = {}
for string in strings:
    ls = len(string)
    if ls in dict_of_len:
        dict_of_len[ls].append(string)
    else:
        dict_of_len[ls] = [string]

To use sets as values, much the same but with a set instead of a list, and with add instead of append.

strings =  ["zone", "abigail", "theta", "form", "libe", "zas"] 
dict_of_len = {}
for string in strings:
    ls = len(string)
    if ls in dict_of_len:
        dict_of_len[ls].add(string)
    else:
        dict_of_len[ls] = {string}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading