将python字典转换为大写
由于某种原因,我的代码拒绝转换为大写,我也不知道为什么。然后,我尝试将字典写入一个文件,并将大写字典值输入到一种模板文件中将python字典转换为大写,python,python-3.x,file,dictionary,file-io,Python,Python 3.x,File,Dictionary,File Io,由于某种原因,我的代码拒绝转换为大写,我也不知道为什么。然后,我尝试将字典写入一个文件,并将大写字典值输入到一种模板文件中 #!/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:
#!/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()
用于将元素的副本作为列表返回)。此外,即使它能工作,它也会保留旧键(另外:在每次迭代中创建字典的速度非常慢…)
相反,在口述理解中重建口述:
newDict = {k.upper():v.upper() for k,v in newDict.items()}
在迭代字典项时不应更改它们。国家:
在字典中添加或删除条目时迭代视图可能会
引发运行时错误
或无法迭代所有条目
根据需要更新词典的一种方法是弹出值并在for
循环中重新赋值。例如:
d = {'abc': 'xyz', 'def': 'uvw', 'ghi': 'rst'}
for k, v in d.items():
d[k.upper()] = d.pop(k).upper()
print(d)
{'ABC': 'XYZ', 'DEF': 'UVW', 'GHI': 'RST'}
另一种方法是词典理解,如。让我猜一下:您正在得到“迭代期间的词典更改”?请包括一个适当的和您在调试时的尝试。