![](/img/trans.png)
[英]Grouping Python dictionary keys as a list and create a new dictionary with this list as a value
[英]Dictionary keys with list value
我想附加到字符串列表中字典中的各個鍵
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']}
我試圖這樣做,但在每個鍵中附加整個列表
votes_dictionary={}
votes_dictionary=votes_dictionary.fromkeys(votes,[])
for i in votes:
print(i.lower())
votes_dictionary[i].append(i)
print(votes_dictionary)
您可以使用defaultdict和list
作為默認值,然后遍歷投票並附加它:
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']}
我看到有三個Eli
,所以通常它看起來像這樣:
output = {}
for name in votes:
output.setdefault(name, [])
output[name].append(name)
print(output)
輸出:
{'johny': ['johny'],
'Eli': ['Eli', 'Eli', 'Eli'],
'Jane': ['Jane'],
'Ally': ['Ally'],
'Johny': ['Johny'],
'john': ['john']}
或者,
import copy
output = copy.deepcopy(mydictionary)
for name in votes:
output[name].append(name)
print(output):
輸出:
{'johny': ['johny'],
'Eli': ['Eli', 'Eli', 'Eli'],
'Johny': ['Johny'],
'Jane': ['Jane'],
'john': ['john'],
'Ally': ['Ally']}
現在,如果您想限制為兩個,即使有三個元素:
output = {}
for name in votes:
# to maintain the order, you can iterate over `mydictionary`
output[name] = [name]*min(2, votes.count(name))
print(output)
輸出:
{'johny': ['johny'],
'Eli': ['Eli', 'Eli'],
'Jane': ['Jane'],
'Ally': ['Ally'],
'Johny': ['Johny'],
'john': ['john']}
實現兩次Eli
另一種有趣方式是itertools.groupby
:
>>> from itertools import groupby
>>> {key: [*group] for key, group in groupby(reversed(votes))}
{'Eli': ['Eli', 'Eli'],
'john': ['john'],
'Johny': ['Johny'],
'Ally': ['Ally'],
'Jane': ['Jane'],
'johny': ['johny']}
votes_dictionary={}
for i in votes:
try:
votes_dictionary[i].append(i)
except KeyError:
votes_dictionary[i] = [i]
print(votes_dictionary)
myDictionary = {'johny': [], 'Eli': [], 'Johny': [], 'Jane': [], 'john': [], 'Ally': []}
votes = ['johny', 'Eli', 'Eli', 'Jane', 'Ally', 'Johny', 'john', 'Eli']
for x in votes:
myDictionary[x].append(x)
votes_dictionary = {}
votes_dictionary = votes_dictionary.fromkeys(votes)
for i in votes:
if not votes_dictionary[i]:
votes_dictionary[i] = []
votes_dictionary[i].append(i)
print(votes_dictionary)
已經發布了很多答案,如果你真的想使用 fromkeys() 方法,你可以做這樣的事情
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.