e.T*_*T55 1 python dictionary list python-3.x
我想附加到字符串列表中字典中的各个键
myDictionary = {'johny': [], 'Eli': [], 'Johny': [], 'Jane': [], 'john': [], 'Ally': []}
votes = ['johny', 'Eli', 'Eli', 'Jane', 'Ally', 'Johny', 'john', 'Eli']
outPut={'johny': ['johny'], 'Eli': ['Eli','Eli'], 'Johny': ['Johny'], 'Jane': ['Jane'], 'john': ['john'], 'Ally': ['Ally']}
Run Code Online (Sandbox Code Playgroud)
我试图这样做,但在每个键中附加整个列表
votes_dictionary={}
votes_dictionary=votes_dictionary.fromkeys(votes,[])
for i in votes:
print(i.lower())
votes_dictionary[i].append(i)
print(votes_dictionary)
Run Code Online (Sandbox Code Playgroud)
You can use defaultdict with list
as default value and then iterate through votes and append it:
from collections import defaultdict
votes = ['johny', 'Eli', 'Eli', 'Jane', 'Ally', 'Johny', 'john', 'Eli']
votes_dictionary = defaultdict(list)
for vote in votes:
votes_dictionary[vote].append(vote)
# votes_dictionary will be an instance of defaultdict
# to convert it to dict, just call dict
print(dict(votes_dictionary))
# outpout
{'johny': ['johny'], 'Eli': ['Eli', 'Eli', 'Eli'], 'Jane': ['Jane'], 'Ally': ['Ally'], 'Johny': ['Johny'], 'john': ['john']}
Run Code Online (Sandbox Code Playgroud)