3

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

cmckeeth
  • 95
  • 2
  • 9
  • I seen a similar stack overflow questioned answered here http://stackoverflow.com/questions/960733/python-creating-a-dictionary-of-lists – user2125630 Mar 16 '17 at 02:13

6 Answers6

6

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']})
Marius
  • 58,213
  • 16
  • 107
  • 105
2

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']}
Psidom
  • 209,562
  • 33
  • 339
  • 356
1

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]
Miriam Farber
  • 18,986
  • 14
  • 61
  • 76
1

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']})
Alex Fung
  • 1,996
  • 13
  • 21
0

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']}
Reza Dodge
  • 174
  • 1
  • 2
  • 4
0

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)
Loki
  • 33
  • 1
  • 9