在没有 import 语句的情况下创建以字符串长度作为键和字符串作为值的字典?

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

你能在没有 import 语句的情况下创建一个以字符串长度为键、字符串为值的字典吗?

使用 import 语句,它看起来像这样:

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)

输出:

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

如果可能的话,我想要两个选项,其中一个选项的值是值列表,另一个选项的值是一组值。

我自己尝试过,但是当同一个键有多个值时,我总是遇到困难。

我的一次失败尝试

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

输出

{3: {'zas'}}

使用 defaultdict 会更容易,但您可以在没有任何导入的情况下完成。

要使用列表作为值:

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]

将集合用作值,大致相同,但使用集合而不是列表,并使用 add 而不是 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}

您可以使用 dict.setdefault:

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

使用dictsetdefault方法:

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)

输出:

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