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

1

6 Answers 6

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']})
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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]

Comments

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

Comments

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

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.