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

Python循环中如何将输入的键批量初始化为字典的0值?

How to Initialize All Team Names as Dictionary Keys with Value 0

Got it, let's sort this out for you! Your current code splits each input line into two team names, but it's not adding those names to your dictionary yet. Here are two straightforward ways to fix this:

Method 1: Update the Dictionary Directly in the Loop

This approach adds each team name to the dictionary right as you process the input. Even if a team name repeats, setting its value to 0 every time is totally fine since we just need an initial value of 0.

myDict = {}
n = 10

for i in range(n):
    # Split the input line into two team names
    t1, t2 = input().split()
    # Add both teams to the dictionary with value 0
    myDict[t1] = 0
    myDict[t2] = 0

# After processing all inputs, myDict will have all unique teams as keys with value 0
print(myDict)

Method 2: Collect Teams First, Then Build the Dictionary

If you prefer a cleaner separation of steps, you can first gather all unique team names in a set (which automatically handles duplicates), then convert that set into a dictionary with values set to 0.

myDict = {}
n = 10
all_teams = set()

for i in range(n):
    t1, t2 = input().split()
    # Add teams to the set (duplicates are ignored automatically)
    all_teams.add(t1)
    all_teams.add(t2)

# Convert the set to a dictionary using a dictionary comprehension
myDict = {team: 0 for team in all_teams}

print(myDict)

What You'll Get

After running either method with your specified 10 inputs, myDict will include every unique team name as a key, each with a value of 0 (order might vary slightly depending on your Python version, but all required keys will be present):

{
    'Truckers': 0,
    'Trekkers': 0,
    'Riders': 0,
    'Bikers': 0,
    'Wanderers': 0,
    'Rovers': 0
}

Both methods work perfectly for your use case—pick whichever one makes more sense to you!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:13:00