python - 逐行打印字典的元素

标签 python

我的文件中有一个字典,我应该编写一个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/

相关文章:

python - 高效查找最长匹配前缀字符串

python - 使用 Python 查找第 N 个素数的枚举

python - 从包含字典的命名元组创建数据帧

python - 使用漂亮的汤来获取html属性值

python - 从 Python 中的图像中删除边框

python - 带有 python 界面的 Dymola - 将结果绘制到文本文件 (.txt) 或类似的文件中

python - Rdflib,Python : Are there any object framing methods to get nested dict/list structure from a graph a-la JSON-LD?

python - 使用scrapy抓取动态内容

python - 如果你不分配它,列表理解的效率如何?

android - 我无法通过谷歌云消息在我的 Android 设备上接收消息?