【问题标题】:Convert python dictionary to uppercase将python字典转换为大写
【发布时间】:2018-10-04 20:53:09
【问题描述】:

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

#!/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 python-3.x file dictionary file-io


【解决方案1】:

在 python 3 中你不能这样做:

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

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

相反,在字典理解中重建你的字典:

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

【讨论】:

  • 为什么newDict} 不够用?我尝试了您的解决方案,它当然可以,但我只是好奇为什么没有 .items() 的版本不起作用。
  • 因为只有newDict 循环迭代键,而不是键/值元组
  • 好吧,所以我猜这是因为myDict.keys() 仅用于键,myDict.values() 仅用于值,myDict.items() 用于键/值元组?顺便说一句 - 是否可以在不循环的情况下将字典键大写?
  • @Konrad 完全正确。 .keys() 真的不是超级有用,因为在 myDict 上进行迭代/测试具有相同的效果。对于“是否可以在不循环的情况下将字典键大写?” => 你必须在每个键上应用 upper() 所以答案是否定的。
【解决方案2】:

您不应该在迭代字典项时更改它们。 docs 状态:

在字典中添加或删除条目时迭代视图可能 引发RuntimeError 或无法遍历所有条目。

根据需要更新字典的一种方法是弹出值并在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'}

另一种方法是字典理解,如shown by @Jean-FrançoisFabre

【讨论】:

    猜你喜欢
    • 2012-10-17
    • 2020-05-08
    • 2020-02-01
    • 2013-02-19
    • 2016-10-16
    • 1970-01-01
    • 2014-11-05
    • 1970-01-01
    • 2017-07-21
    相关资源
    最近更新 更多