【问题标题】:How to create a dictionary from a given list?如何从给定列表创建字典?
【发布时间】:2020-09-21 13:12:44
【问题描述】:

我正在尝试从我给定的列表中创建一个字典,知道键将是该单词的第一个字母,并且具有相同首字母的那些将相应地添加到 1 个键。请大家帮帮我好吗?

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

【问题讨论】:

  • 这能回答你的问题吗? Converting Dictionary to List?
  • 你是什么意思:“将相应地添加到 1 个键”?你能展示你的预期结果吗?

标签: python dictionary


【解决方案1】:
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

【讨论】:

    【解决方案2】:

    更pythonic的解决方案:

    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)
    

    输出

    {
        "a": ["apple"],
        "b": ["bible", "bird"],
        "c": ["candy"],
        "d": ["day"],
        "e": ["elephant"],
        "f": ["friend"],
    }
    

    【讨论】:

      【解决方案3】:

      只是另一种选择:

      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))
      

      结果:

      {'a': ['apple'], 'b': ['bible', 'bird'], 'c': ['candy'], 'd': ['day'], 'e': ['elephant'], 'f': ['friend']}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-01
        • 1970-01-01
        • 2022-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-03
        • 2018-12-17
        相关资源
        最近更新 更多