简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM