逐行打印字典元素

时间:2013-12-07 20:33:06

标签: 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)

3 个答案:

答案 0 :(得分:2)

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(':')会做你想要的,而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:]

答案 1 :(得分:0)

如果您尝试使用不起作用的标准dict以与文件中出现的顺序相同的顺序打印字典中的键值(python dict对象不保持顺序)。假设你想按照dicts值的值打印......

lines = ["the 1", "and 2"]
d = {}

for l in lines:
    k, v = l.split()
    d[k] = v

for key in sorted(d, key=d.get, reverse=True):
    print ":".join([key, d[key]])

假设您可以使用lambda和字符串连接。

lines = ["the 1", "and 2"]
d = {}

for l in lines:
    k, v = l.split()
    d[k] = v

for key in sorted(d, key=lambda k: d[k], reverse=True):
    print key + ":" + d[key]

没有lambda

for value, key in sorted([(d[k], k) for k in d], reverse=True):
    print key + ":" + value

用它来制作一个功能

def lines_to_dict(lines):
    return_dict = {}
    for line in lines:
        key, value = line.split()
        return_dict[key] = value

    return return_dict

if __name__ == "__main__":

    lines = ["the 1", "and 2"]
    print lines_to_dict(lines)

答案 2 :(得分:0)

只要键/值都是字符串,就可以解析字典并提取元素。请注意,由于这实际上并不创建字典,因此会保留重复的元素和订单 - 您可能希望这样做。

import ast

text = '{"the":"1", "and":"2"}'
d = ast.parse(text).body[0].value
for k, v in zip(d.keys, d.values):
    print '{}:{}'.format(k.s, v.s)