python create dict using list of strings with length of strings as values

旧城冷巷雨未停 提交于 2021-02-04 19:32:05

问题


I'm sure this can be done, but I have thus far been unsuccessful:

I have a list of strings. I want to create a dictionary with the length of said strings (which can be expressed as a range) as the key and the string itself as the value.

example: Here's something like the list I have: ['foo','bar','help','this','guy']

I'd like to end up with a dictionary like this: {3:['foo','bar','guy], 4:['this','help']}


回答1:


You can use a dictionary as a container with setdefault:

lst = ['foo','bar','help','this','guy'] 

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

result
# {3: ['foo', 'bar', 'guy'], 4: ['help', 'this']}



回答2:


Using defaultdict so you don't have to check whether or not to create the list for a new key:

from collections import defaultdict

x = ['foo','bar','help','this','guy']

len_dict = defaultdict(list)

for word in x:
    len_dict[len(word)].append(word)

len_dict
#
# Out[5]: defaultdict(list, {3: ['foo', 'bar', 'guy'], 4: ['help', 'this']})



回答3:


You can do it like that:

d={}
lst=['foo','bar','help','this','guy']
for i in lst:
    if len(i) in d:
        d[len(i)].append(i)
    else:
        d[len(i)]=[i]



回答4:


This solution is pythonic, elegant and fast: (by the Famous Raymond Hettinger in one of his many conferences).

dict.setdefault is the dictionary method that initialises a key-value if the key is not found in dict as well as performing dict.get for provided key.

l = ['foo','bar','help','this','guy']
d = {}
for e in l:
    key = len(e)
    d.setdefault(key, []).append(name)
print(d)

Output:

{3: ['foo', 'bar', 'guy'], 4: ['help', 'this']}

This solution is the modern way of the solution above:

defaultdict from collection is a subclass of dict that automatically initialises value to any given key that is not in the defaultdict.

from collections import defaultdict
l = ['foo','bar','help','this','guy']
d = defaultdict(list)
for e in l:
    key = len(e)
    d[key].append(e)
print(d)

Output:

defaultdict(<class 'list'>, {3: ['foo', 'bar', 'guy'], 4: ['help', 'this']})



回答5:


Similar to what have been said, but using the get method of dict class:

the_list=['foo','bar','help','this','guy']
d = {}
for word in the_list:
  key = len(word)
  d[key] = d.get(key, []) + [word]
print(d)
# {3: ['foo', 'bar', 'guy'], 4: ['help', 'this']}



回答6:


Another approach:

from collections import defaultdict
given_list=['foo','bar','help','this','guy']
len_words=[len(i) for i in given_list]
d=defaultdict(list)
for i,j in list(zip(len_words,given_list)):
    d[i].append(j)


来源:https://stackoverflow.com/questions/42824080/python-create-dict-using-list-of-strings-with-length-of-strings-as-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!