Nguyen Au Quang Loc
Nguyen Au Quang Loc

Reputation: 1

How to create a dictionary from a given list?

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

Upvotes: 0

Views: 92

Answers (3)

emremrah
emremrah

Reputation: 1765

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

Upvotes: 1

Jay Mody
Jay Mody

Reputation: 4033

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"],
}

Upvotes: 6

ptan9o
ptan9o

Reputation: 304

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

Upvotes: 2

Related Questions