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

Python新手求助:如何将文本文件每行转为字典条目?

解决你的Python字典转换与KeyError问题

Hey there! Let's tackle your two issues one by one—first the frustrating KeyError, then automating that tedious manual formatting for your dictionary code.

一、Fixing the KeyError

The root cause here is a type mismatch: when you read lines from your text file, the keys (like 1, 2) are stored as strings in your dictionary, but random.randint(1,100) returns an integer. Python treats string '1' and integer 1 as completely different keys, hence the KeyError.

You can fix this in two easy ways:

Option 1: Convert keys to integers when building the dictionary

Modify your existing code to parse the key as an integer instead of keeping it as a string:

action_table2 = {}
with open('action_table2.txt') as f:
    for line in f:
        # Split the line, strip whitespace, and convert key to int
        key_str, value = line.strip().split(':')
        key = int(key_str)
        # Also strip extra spaces from the value (like " Goals" → "Goals")
        action_table2[key] = value.strip()

# Now this will work!
import random
print(action_table2[random.randint(1,100)])

Option 2: Convert the random integer to a string when accessing the dictionary

If you prefer to keep keys as strings (maybe for consistency with other parts of your code), just convert the random number to a string before looking it up:

import random
print(action_table2[str(random.randint(1,100))])

二、Automating the Manual Dictionary Formatting

No more copying-pasting and adding quotes/comma manually! Here's a small script that reads your text file and outputs a ready-to-use dictionary code block you can directly copy into your project:

with open('action_table2.txt') as f:
    print("action_table2 = {")
    for line in f:
        key, value = line.strip().split(':')
        value_clean = value.strip()
        # Format each line with quotes and a trailing comma
        print(f"    '{key}': '{value_clean}',")
    print("}")

When you run this, it will print something like:

action_table2 = {
    '1': 'Goals',
    '2': 'Dreams',
    '3': 'Environment',
    ...
}

Just copy this output and paste it into your Python file—done! This works for any similar text files you need to process, saving you tons of time.

Bonus Tip

If your values might contain apostrophes (like Don't), using double quotes for the value string would avoid syntax errors. Just adjust the print line to:

print(f'    "{key}": "{value_clean}",')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:58:05