具有列表值的字典键

2024-06-16 13:41:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在字符串列表中添加到字典中的各个键

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)

Tags: 字符串列表outputdictionary字典johnprintvotes
3条回答

我看到有三个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的另一个有趣方法是,^{}

>>> 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)

您可以使用带有listdefaultdict作为默认值,然后迭代投票并附加它:

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']}

相关问题 更多 >