Python 如何创建到一组值的字典映射以避免dict中的相同键
我有一本字典,它将一个单词映射到该单词在文本中出现的频率:Python 如何创建到一组值的字典映射以避免dict中的相同键,python,dictionary,set,Python,Dictionary,Set,我有一本字典,它将一个单词映射到该单词在文本中出现的频率: {'loves' : 3, 'coding' : 3} “爱”和“编码”这两个词在文本中出现了3次,因此具有相同的价值。现在我们知道,如果要交换此字典中的键和值,它将返回以下内容: 或者 {3:'loves'} 还是这个 {3:'coding'} 因为字典中不允许使用相同的键 现在我的问题是如何交换字典中的键和功能,同时避免重复键,如下所示: {3: {'loves', 'coding'}} 这是我失败的尝试: def
{'loves' : 3, 'coding' : 3}
“爱”和“编码”这两个词在文本中出现了3次,因此具有相同的价值。现在我们知道,如果要交换此字典中的键和值,它将返回以下内容:
或者
{3:'loves'}
还是这个
{3:'coding'}
因为字典中不允许使用相同的键
现在我的问题是如何交换字典中的键和功能,同时避免重复键,如下所示:
{3: {'loves', 'coding'}}
这是我失败的尝试:
def func(text, words):
d = dict()
for word in text.split():
if word in words:
if word in d:
d[word] += 1
elif word not in d:
d[word] = 1
# return d
newDict = dict()
for key in d:
newKey = d[key]
newDict[newKey] = set()
newDict[newKey].add(key)
return newDict
编辑:
谢谢你所有有价值的回答。我还修复了下面的bug:在bug行旁边添加了一条注释
# swapping keys and values in a dictionary:
newDict = dict()
def func(text, words):
d = dict()
for word in text.split():
if word in words:
if word in d:
d[word] += 1
elif word not in d:
d[word] = 1
# return d
newDict = dict()
for key in d:
if d[key] not in newDict:
newDict[d[key]] = set({key}) # This was my bug. Initially I had
# newDict[d[key]] = set()
elif d[key] in newDict:
newDict[d[key]].add(key)
return newDict
现在,如果我在以下输入上运行它:
func('Ahmed loves loves coding coding is rewarding', {'loves', 'coding', 'I'})
我得到的正是我想要的:
{2: {'coding', 'loves'}}
首先,
“爱”和“编码”两个词在文本中出现了3次,因此具有相同的键
它们实际上具有相同的值,而不是相同的键(可能您键入错误?)
但是,您只需对执行一个简单的循环,然后执行一个简单的逻辑,首先检查新的dict中是否存在该值;它确实如此,附加到它们的价值上;如果没有,则创建一个新条目
d = {'loves' : 3, 'coding' : 3}
new_dict = {}
for key, value in d.items():
if new_dict.get(value, None):
new_dict[value].add(key)
else:
new_dict[value] = {key}
在@RafaelC的回答中,仅使用集合:
d = {'loves' : 3, 'coding' : 3}
new_dict = {}
for key, value in d.items():
if value not in new_dict:
new_dict[value].add(key)
else:
new_dict[value] = {key}
我的答案使用set
:}。我刚发完帖子就编辑了它,你可以用它作为替代品。