将字符串中的每个字符转换为字典键

11

假设我有一个字符串"abcdefghijklmnopqrstuvwxyz",我想用这些值来初始化字典键。

alphabet = 'abcdefghijklmnopqrstuvwxyz'

alphabetDict = dict()
for char in alphabet:
    alphabetDict[char] = 0

有没有更好的方式做这件事?


https://dev59.com/AHI-5IYBdhLWcg3wpaJ1 - Mathieu Borderé
6个回答

21

你可以使用dict.fromkeys()方法 -

>>> s = 'abcdefghijklmnopqrstuvwxyz'
>>> alphaDict = dict.fromkeys(s,0)
>>> alphaDict
{'m': 0, 'p': 0, 'i': 0, 'n': 0, 'd': 0, 'w': 0, 'k': 0, 'y': 0, 's': 0, 'b': 0, 'h': 0, 't': 0, 'u': 0, 'q': 0, 'g': 0, 'l': 0, 'e': 0, 'a': 0, 'j': 0, 'c': 0, 'o': 0, 'f': 0, 'v': 0, 'x': 0, 'z': 0, 'r': 0}

来自 文档 -

fromkeys(seq[, value])

使用seq中的键创建一个新字典,值设置为value。

fromkeys()是一个类方法,返回一个新字典。value默认为None

请注意,如果value是可变的,比如list或另一个dict等,则不应使用此方法。因为当调用fromkeys()方法时,该值仅被计算一次,并且所有键都指向同一个对象。

您可以将不可变类型作为value使用,例如intstr等。


此外,您不需要指定字符串salphabet,相反,您可以使用string.ascii_lowercase。例如 -
>>> import string
>>> alphaDict = dict.fromkeys(string.ascii_lowercase,0)
>>> alphaDict
{'m': 0, 'p': 0, 'i': 0, 'n': 0, 'd': 0, 'w': 0, 'k': 0, 'y': 0, 's': 0, 'b': 0, 'h': 0, 't': 0, 'u': 0, 'q': 0, 'g': 0, 'l': 0, 'e': 0, 'a': 0, 'j': 0, 'c': 0, 'o': 0, 'f': 0, 'v': 0, 'x': 0, 'z': 0, 'r': 0}

6
你可以在Python中使用字典推导式。
alphabetDict = {char: 0 for char in alphabet}

字典(Python文档)

这个答案和Anand上面的略有不同。字典推导式会为每个键计算值,而fromkeys只会计算一次。如果你使用像整数这样的元素,这不会造成问题。但是,如果你这样做:

d = {key: [] for key in <some set>}
d[3].append(5)
print(d[2])

提供给您

[]

如果您有不同的列表,同时

d = dict.fromkeys(<some set>, [])
d[3].append(5)
print(d[2])

提供给您
[5]

将所有键映射到同一列表。


3

是的,您可以使用字典推导式在一行中完成此操作。

In [1]: alphabet = 'abcdefghijklmnopqrstuvwxyz'

In [2]: {x:0 for x in alphabet} # dictionary comprehension
Out[2]: 
{'a': 0,
 'b': 0,
 'c': 0,
 'd': 0,
 'e': 0,
 'f': 0,
 'g': 0,
 'h': 0,
 'i': 0,
 'j': 0,
 'k': 0,
 'l': 0,
 'm': 0,
 'n': 0,
 'o': 0,
 'p': 0,
 'q': 0,
 'r': 0,
 's': 0,
 't': 0,
 'u': 0,
 'v': 0,
 'w': 0,
 'x': 0,
 'y': 0,
 'z': 0}

0

尝试了另一种方法。

dict(zip(alphabets, '0'*len(alphabets)))

0
如果您需要一个具有不同值而不是常量值的字典,可以使用随机模块创建如下所示的字典:
>>> import random
>>> alphabet = 'abcdefghijklmnopqrstuvwxyz'
>>> my_dict = dict([ (ch, random.randint(1,len(alphabet)) ) for ch in alphabet ]  )
>>> my_dict
{'a': 17, 'b': 15, 'c': 3, 'd': 5, 'e': 5, 'f': 13, 'g': 7, 'h': 1, 'i': 3, 'j': 12, 'k': 11, 'l': 7, 'm': 8, 'n': 23, 'o': 15, 'p': 7, 'q': 9, 'r': 19, 's': 17, 't': 22, 'u': 20, 'v': 24, 'w': 26, 'x': 14, 'y': 7, 'z': 24}
>>>

当我需要一个带有随机值的字典进行测试时,我会像上面那样创建字典。
另一种创建字典的方法是将文本中的每个字符及其计数放入其中。
>>> char_count = lambda text, char: text.count(char)
>>> text = "Genesis 1 - 1 In the beginning God created the heavens and the earth. 2 Now the earth was formless and desolate, and there was darkness upon the surface of the watery deep, and God's active force was moving about over the surface of the waters."
>>> my_dict = dict( [ ( char, char_count(text, char) ) for char in text ]  )
>>> my_dict
{'G': 3, 'e': 32, 'n': 13, 's': 15, 'i': 5, ' ': 45, '1': 2, '-': 1, 'I': 1, 't': 17, 'h': 12, 'b': 2, 'g': 3, 'o': 12, 'd': 10, 'c': 5, 'r': 12, 'a': 19, 'v': 4, '.': 2, '2': 1, 'N': 1, 'w': 6, 'f': 6, 'm': 2, 'l': 2, ',': 2, 'k': 1, 'u': 4, 'p': 2, 'y': 1, "'": 1}

解释:
1. lambda函数计算字符出现的次数。
2. 对于文本中的每个字符调用lambda函数,以获取该特定字符的计数。

注意:您可以改进此代码,以避免对重复字符进行重复调用。

使用字典推导式可能比以上所有方法都更简单:

{ char:(text.count(char)) for char in text }

0
为了避免重复,正如@Robert Ranjan所提到的,我们采用这种方式。
>>> import string
>>> char_count = lambda text, char: text.count(char)
>>> allAscii = list(string.printable)
>>> # alphabet = 'abcdefghijklmnopqrstuvwxyz'
>>> text = "Genesis 1 - 1 In the beginning God created the heavens and the earth. 2 Now the earth was formless and desolate, and * @ there was darkness upon the surface of the watery deep, and God's active force was moving about over the surface of the waters."
>>> # my_dict = dict( [ ( char, char_count(text, char) ) for char in alphabet]  
>>> my_dict = dict( [ ( char, char_count(text, char) ) for char in allAscii]
>>> for eachKey in my_dict:  
        print(repr(eachKey), ': ', my_dict[eachKey], ' ', end=' || ')    
'0' :  0   || '1' :  2   || '2' :  1   || '3' :  0   || '4' :  0   || '5' :  0   || '6' :  0   || '7' :  0   || '8' :  0   || '9' :  0   || 'a' :  19   || 'b' :  2   || 'c' :  5   || 'd' :  10   || 'e' :  32   || 'f' :  6   || 'g' :  3   || 'h' :  12   || 'i' :  5   || 'j' :  0   || 'k' :  1   || 'l' :  2   || 'm' :  2   || 'n' :  13   || 'o' :  12   || 'p' :  2   || 'q' :  0   || 'r' :  12   || 's' :  15   || 't' :  17   || 'u' :  4   || 'v' :  4   || 'w' :  6   || 'x' :  0   || 'y' :  1   || 'z' :  0   || 'A' :  0   || 'B' :  0   || 'C' :  0   || 'D' :  0   || 'E' :  0   || 'F' :  0   || 'G' :  3   || 'H' :  0   || 'I' :  1   || 'J' :  0   || 'K' :  0   || 'L' :  0   || 'M' :  0   || 'N' :  1   || 'O' :  0   || 'P' :  0   || 'Q' :  0   || 'R' :  0   || 'S' :  0   || 'T' :  0   || 'U' :  0   || 'V' :  0   || 'W' :  0   || 'X' :  0   || 'Y' :  0   || 'Z' :  0   || '!' :  0   || '"' :  0   || '#' :  0   || '$' :  0   || '%' :  0   || '&' :  0   || "'" :  1   || '(' :  0   || ')' :  0   || '*' :  1   || '+' :  0   || ',' :  2   || '-' :  1   || '.' :  2   || '/' :  0   || ':' :  0   || ';' :  0   || '<' :  0   || '=' :  0   || '>' :  0   || '?' :  0   || '@' :  1   || '[' :  0   || '\\' :  0   || ']' :  0   || '^' :  0   || '_' :  0   || '`' :  0   || '{' :  0   || '|' :  0   || '}' :  0   || '~' :  0   || ' ' :  47   || '\t' :  0   || '\n' :  0   || '\r' :  0   || '\x0b' :  0   || '\x0c' :  0   ||
>>> 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接