在字典中搜索一个键,将该键的值添加到另一个键值

2024-09-29 17:09:54 发布

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

好吧,比如说,我有一本字典,里面有很多键:值对:

   worddict = {'example1': 1, 'example2': 0, 'example3': 7}

我想检查某些键,得到它们的值,并将其添加到另一个键:值对的值。例如:

伪代码:

seconddict = {'firstitem': 1, 'seconditem': 1, 'thirditem':9}

for x in worddict:
    if x.key = example1:
        seconddict{'firstitem'.value} + example1.value

我想我的想法是对的,但语法不对。你知道吗

但基本上,firstitem的值会增加与example1的值完全相同的数字

基本上,我有一个单词列表,这些单词在某些类别中。这些类别中的任何一个单词都会将该类别的值加1。你知道吗

编辑:

预期的输出是,如果第一个字典中的键有一个值,则该值将被添加到第二个字典中特定键的值中。你知道吗

所以在本例中,firstitem的值将变为“2”,因为它从1开始,而example1属于“firstname”类别。你知道吗


Tags: 代码infor字典value类别单词example1
3条回答

你是这么想的吗?你知道吗

for word,category in worddict.items():
    categoryCounts[category] += 1

我猜你正在寻找这样的东西-如果没有,请张贴你的预期输出是什么

my_list = [False, False, False, True, True, True]

worddict = {'example1': 1, 'example2': 0, 'example3': 7}
seconddict = {'firstitem': 1, 'seconditem': 1, 'thirditem':9}

keys_to_add = ['example1', 'example3']

for k in keys_to_add:
    seconddict['firstitem'] += worddict[k]

print seconddict

编辑:OP的评论明确指出单词可以属于多个类别。代码已调整。你知道吗


我想你应该把单词的值按类别累加起来。一种(简单的)方法是:

def accumulate_by_category(word_values, cat_sums, cats):
    """ modify the category sums by adding the values of the given words """
    for word, value in word_values.items():
        for cat in cats[word]:
            cat_sums[cat] += value

你可以这样使用它:

worddict = {'example1': 1, 'example2': 0, 'example3': 7}
seconddict = {'firstitem': 1, 'seconditem': 1, 'thirditem':9}

categories = {'example1': ['firstitem', 'thirditem'],
              'example2': ['seconditem', 'thirditem'],
              'example3': ['thirditem']}

accumulate_by_category(worddict, seconddict, categories)
print(seconddict) # {'seconditem': 1, 'firstitem': 2, 'thirditem': 17}

相关问题 更多 >

    热门问题