0

I am trying to create a dictionary from my given list, knowing that the key will be the first letter of that word, and those have the same first letter would be added up to 1 key correspondingly. Can you guys help me out, please?

words= ['apple', 'bible','bird' ,'candy', 'day', 'elephant','friend']
mincrmatt12
  • 382
  • 3
  • 12
  • Does this answer your question? [Converting Dictionary to List?](https://stackoverflow.com/questions/1679384/converting-dictionary-to-list) – GutZuFusss Jun 02 '20 at 22:59
  • What do you mean by: "would be added up to 1 key correspondingly"? Could you show your expected result ? – Sylvaus Jun 02 '20 at 23:05

3 Answers3

6

A more pythonic solution:

import collections

words= ['apple', 'bible','bird' ,'candy', 'day', 'elephant','friend']

d = collections.defaultdict(list)

for w in words:
    d[w[0]].append(w)

d = dict(d)

Output

{
    "a": ["apple"],
    "b": ["bible", "bird"],
    "c": ["candy"],
    "d": ["day"],
    "e": ["elephant"],
    "f": ["friend"],
}
Jay Mody
  • 3,727
  • 1
  • 11
  • 27
2
words= ['apple', 'bible','bird' ,'candy', 'day', 'elephant','friend']

def make_dict(words):
    di = {}
    for item in words:
        if item[0] in di:
            di[item[0]] += [item]
        else:
            di[item[0]] = [item]
    return di
ptan9o
  • 174
  • 9
1

Just another option:

from collections import defaultdict

words = ['apple', 'bible','bird' ,'candy', 'day', 'elephant','friend']

word_dict = defaultdict(lambda: [])

list(map(lambda word: word_dict[word[0]].append(word), words))

print(dict(word_dict))

Results in:

{'a': ['apple'], 'b': ['bible', 'bird'], 'c': ['candy'], 'd': ['day'], 'e': ['elephant'], 'f': ['friend']}
emremrah
  • 1,733
  • 13
  • 19