Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

python 3.x - Appending multiple values to dictionary appends "None"

I try to add a list to a dictionary key, but when I append a value, it returns the value None. I have also tried collections.defaultdict(list) without success.

Code:

text = "ABBBAACCCCAABBCCCCAABCBCBCABCCCA"
chain = dict()

for i in range (0, text.__len__()-1):
    key = text[i : i+1]
    next_word = text[i +1 : i +2]

    if key not in chain.keys():
        chain.setdefault(key)
    else:
        chain.setdefault(key, [].append(next_word))

    print(key, next_word, chain[key], chain)

Output:

A B None {'A': None}
B B None {'B': None, 'A': None}
B B None {'B': None, 'A': None}
B A None {'B': None, 'A': None}
…
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

[].append() returns None. You'd want to append to the return value of dict.setdefault() instead. You also don't need to do a key containment test when using dict.setdefault(); setdefault() already makes that test for you.

Next, don't call object.__len__(). Use len(object) instead. I'd also use {} instead of dict(); the latter has to look up a name and make a function call, the {} literal is compiled to a single bytecode to create a dictionary.

This works:

for i in range(len(text) - 1):
    key = text[i:i + 1]
    next_word = text[i + 1:i + 2]

    chain.setdefault(key, []).append(next_word)

You could also use zip() to pair up the letters:

for key, next_word in zip(text, text[1:]):
    chain.setdefault(key, []).append(next_word)

Demo:

>>> text = "ABBBAACCCCAABBCCCCAABCBCBCABCCCA"
>>> chain = {}
>>> for key, next_word in zip(text, text[1:]):
...     chain.setdefault(key, []).append(next_word)
...
>>> chain
{'A': ['B', 'A', 'C', 'A', 'B', 'A', 'B', 'B'], 'B': ['B', 'B', 'A', 'B', 'C', 'C', 'C', 'C', 'C'], 'C': ['C', 'C', 'C', 'A', 'C', 'C', 'C', 'A', 'B', 'B', 'A', 'C', 'C', 'A']}
>>> from pprint import pprint
>>> pprint(chain)
{'A': ['B', 'A', 'C', 'A', 'B', 'A', 'B', 'B'],
 'B': ['B', 'B', 'A', 'B', 'C', 'C', 'C', 'C', 'C'],
 'C': ['C', 'C', 'C', 'A', 'C', 'C', 'C', 'A', 'B', 'B', 'A', 'C', 'C', 'A']}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...