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:
{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}