I have a list of words like
["abc","hello","i"]
and I want to store these in a dictionary where the key is the length of the word.
I have only gotten as far as initializing the dictionary.
I have a list of words like
["abc","hello","i"]
and I want to store these in a dictionary where the key is the length of the word.
I have only gotten as far as initializing the dictionary.
Use itertools.groupby function, and a dict expression to build the result. The pythonic way
>>> from itertools import groupby
>>> data=["abc","a", "bca", "hello","i"] #more than one result by word-length
>>> keyfunc = lambda x:len(x)
>>> data = sorted(data, key=keyfunc)
>>> {k:list(g) for k, g in groupby(data,keyfunc)}
{1: ['a', 'i'], 3: ['abc', 'bca'], 5: ['hello']}
In the old days before defaultdict
, we use to write where l
is the list of words:
d = {}
for w in l:
if len(w) in d:
d[len(w)].append(w)
else:
d[len(w)] = [w]
Which results in d
being {1: ['i'], 3: ['abc'], 5: ['hello']}
.
With defaultdict
:
from collections import defaultdict
d = defaultdict(list)
for w in l:
d[len(w)].append(w)
Which results in d
being defaultdict(<type 'list'>, {1: ['i'], 3: ['abc'], 5: ['hello']})
. And can be easily turned into a dict
via dict(d)
, resulting in {1: ['i'], 3: ['abc'], 5: ['hello']}
.
You just have to
array = ["abc","hello","i"]
dict = {}
for i in array:
dict[len(i)] = i
The main problem is that in a dictionary can be put only one value per key, so if you have more than one word that have the same length, only the last world you put in will be saved.
words = {}
words[3] = "abc"
words[5] = "hello"
words[1] = "i"
Similarly, it can be done with the following code:
d = {}
l = ["abc","hello","i"]
for item in l:
d.setdefault(len(item), []).append(item)
you can try following code:
dict = {}
elements = ["varun","rahul","rishabh"]
for item in elements:
dict.setdefault(len(item), []).append(item)
Using a comprehension:
mydict = {len(i): i for i in list_of_words}
Edit: for updated OP needs this is not useful - it only records one word per word length key. I can't figure out how to do the equivalent of perl's
push @list, value
with autovivification.