【问题标题】:how to convert list to dictionary? [closed]如何将列表转换为字典? [关闭]
【发布时间】:2017-09-12 08:22:42
【问题描述】:

我有这个:

l = ["a" ,"b" ,"c" ,"d" ,"e" ,"i" ,"i" ,"e"]

我想要这样,每个键的数量:

 l =  {"a":"1", "b":"1", "c":"1", "d":"1", "e":"2" ,"i":"2"}

【问题讨论】:

  • 是否要统计列表中的元素?

标签: python list dictionary


【解决方案1】:
>>> from collections import Counter
>>> l = ["a", "b", "c", "d", "e", "i", "i", "e"]
>>> Counter(l)
Counter({'e': 2, 'i': 2, 'a': 1, 'c': 1, 'b': 1, 'd': 1})

【讨论】:

  • 太快了。
【解决方案2】:

.get() 方法可用于计数https://www.tutorialspoint.com/python/dictionary_get.htm

下面的行创建了两个变量,你的列表和一个空字典:

l, dct = ["a", "b", "c", "d", "e" ,"i" , "i", "e"], {}

然后遍历列表中的每个元素并使用 .get() 检查字典“键”是否存在,如果不存在,它将创建它,如果它不存在,则设置默认“值” ":

for element in l: dct [element] = dct.get(element, 0)+1

在上述情况下,如果键不存在,则默认值为 0,如果确实存在,它将 +1 字典键 [元素] 的现有值

然后打印字典

print (dct)

打印:

{'i': 2, 'd': 1, 'c': 1, 'b': 1, 'a': 1, 'e': 2}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 2022-01-03
    • 2014-01-30
    • 2011-07-11
    相关资源
    最近更新 更多