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

Time:02-01

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'}}

CodePudding user response:

You can use dict.setdefault:

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

CodePudding user response:

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}

CodePudding user response:

Use setdefault method of dict:

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

# List version
dict_of_len = {}
for word in strings:
    dict_of_len.setdefault(len(word), []).append(word)
print(dict_of_len)


# Sets version
dict_of_len = {}
for word in strings:
    s = dict_of_len.setdefault(len(word), set())
    dict_of_len[len(word)] = s.union([word])
print(dict_of_len)

Output:

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