gpt4 book ai didi

python - 将python字典转换为大写

转载 作者:行者123 更新时间:2023-12-03 18:37:42 24 4
gpt4 key购买 nike

出于某种原因,我的代码拒绝转换为大写,我不知道为什么。我试图然后将字典写入文件,并将大写字典值输入到某种模板文件中。

#!/usr/bin/env python3
import fileinput
from collections import Counter


#take every word from a file and put into dictionary
newDict = {}
dict2 = {}
with open('words.txt', 'r') as f:
for line in f:
k,v = line.strip().split(' ')
newDict[k.strip()] = v.strip()
print(newDict)
choice = input('Enter 1 for all uppercase keys or 2 for all lowercase, 3 for capitalized case or 0 for unchanged \n')
print("Your choice was " + choice)

if choice == 1:
for k,v in newDict.items():
newDict.update({k.upper(): v.upper()})
if choice == 2:
for k,v in newDict.items():
dict2.update({k.lower(): v})


#find keys and replace with word

print(newDict)
with open("tester.txt", "rt") as fin:
with open("outwords.txt", "wt") as fout:
for line in fin:
fout.write(line.replace('{PETNAME}', str(newDict['PETNAME:'])))
fout.write(line.replace('{ACTIVITY}', str(newDict['ACTIVITY:'])))

myfile = open("outwords.txt")
txt = myfile.read()
print(txt)
myfile.close()

最佳答案

在 python 3 中你不能这样做:

for k,v in newDict.items():
newDict.update({k.upper(): v.upper()})

因为它在迭代时更改了字典,而 python 不允许这样做(python 2 不会发生这种情况,因为 items() 用于将元素的副本作为 list 返回)。此外,即使它有效,它也会保留旧键(还有:在每次迭代时创建字典非常慢......)

相反,在字典理解中重建你的字典:
newDict = {k.upper():v.upper() for k,v in newDict.items()}

关于python - 将python字典转换为大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50004310/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com