我的文件中有一个字典,我应该编写一个Python代码来在单独的行中打印键和值。(不使用.keys()和.values()。
例如: dict={"the":"1", "and":"2"} 应返回为
the:1
and:2
这是我尝试过的代码。我是 python 字典的新手。请帮我解决这个问题。
dict2 = {}
f= open("dict.txt", 'r')
for line in f:
it = line.split()
k, v = it[0], it[1:]
dict2[k] = v
return (dict2)
最佳答案
line.split()
按空格分割。您可能需要 line.split(':')
。
>>> "the:1".split()
['the:1']
>>> "the:1".split(':')
['the', '1']
另请注意
it = line.split(':')
k, v = it[0], it[1:]
可以简化为
k, v = line.split(':')
编辑:实际上这两个做不同的事情,但是 line.split()
应该只有 2 个元素,k, v = line.split(':')
code> 将执行您想要的操作,而 it[1:]
将返回 ['1']
而不是 '1'
。
虽然我猜想更优雅地处理解析问题,你可以这样做:
it = line.split()
if len(it) != 2:
print "Error!"
k, v = it[0], it[1] # note it[1] and not it[1:]
关于python - 逐行打印字典的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20446282/