You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.x中通过乘法处理含元组的两个字典问题

Fixing the IndexError and Correcting the Dictionary Transformation

Let's break down what's going wrong with your current code and how to fix it to get the desired d3 dictionary.

Issues in Your Existing Code

  1. Incorrect Comparison in List Comprehension: You're comparing key (the integer keys from d1, like 1, 2, etc.) to currVal (animal names like 'dog'), which will never match. This leaves num as an empty list, causing the IndexError when you try to access num[0].
  2. Only Processing the First Tuple: Your code only looks at val[0] (the first tuple in each list), but you need to process every tuple in the list for each key in d1.
  3. Immutable Tuples: Tuples can't be modified in place—you need to create new tuples with the updated values instead of trying to overwrite the second element of an existing tuple.

Corrected Code

Here's a working solution that addresses all these issues:

d2 = {'dog': 1.0, 'bird': 0.0, 'egret': 2.0, 'aardvark': 1.0, 'cat': 3.0, 'fish': 2.0}
d1 = {1: [('dog', 3), ('bird', 1)], 2: [('egret', 1), ('aardvark', 1), ('cat', 1), ('bird', 2)], 3: [('dog', 1), ('aardvark', 5), ('fish', 3), ('bird', 1)], 4: [('dog', 1), ('aardvark', 2), ('fish', 3), ('bird', 1)], 5: [('egret', 2), ('bird', 1)], 6: [('bird', 1)], 7: [('dog', 5), ('bird', 6)], 8: [('aardvark', 1), ('bird', 8)]}

d3 = {}
for key, tuples_list in d1.items():
    updated_tuples = []
    for animal, count in tuples_list:
        # Get the multiplier from d2 using the animal as the key
        multiplier = d2[animal]
        # Calculate the new count and create a new tuple
        updated_count = count * multiplier
        updated_tuples.append((animal, updated_count))
    # Assign the updated list to the corresponding key in d3
    d3[key] = updated_tuples

# Verify the result
print(d3)

How This Works

  • We initialize an empty dictionary d3 to store our results.
  • For each key-value pair in d1, we iterate over every tuple in the list of tuples.
  • For each tuple, we use the animal name to look up the multiplier in d2, compute the updated count, and create a new tuple with the original animal and updated count.
  • We collect all these updated tuples into a list and assign it to the same key in d3.

Result

Running this code will produce exactly the d3 dictionary you're aiming for:

{1: [('dog', 3.0), ('bird', 0.0)], 2: [('egret', 2.0), ('aardvark', 1.0), ('cat', 3.0), ('bird', 0.0)], 3: [('dog', 1.0), ('aardvark', 5.0), ('fish', 6.0), ('bird', 0.0)], 4: [('dog', 1.0), ('aardvark', 2.0), ('fish', 6.0), ('bird', 0.0)], 5: [('egret', 4.0), ('bird', 0.0)], 6: [('bird', 0.0)], 7: [('dog', 5.0), ('bird', 0.0)], 8: [('aardvark', 1.0), ('bird', 0.0)]}

内容的提问来源于stack exchange,提问作者artemis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:08:56