簡體   English   中英

逐行打印字典中的元素

[英]Printing elements of dictionary line by line

我在文件中有字典,我應該編寫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()分割。 您可能需要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:]

如果您嘗試使用不起作用的標准字典以與它們在文件中出現的順序相同的順序從字典中打印鍵值(python dict對象不保持順序)。 假設您要按字典值打印...

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)

只要鍵/值都是字符串,就可以解析字典並提取元素。 注意,由於這實際上並沒有創建字典,因此重復的元素和順序得以保留-您可能要考慮到這一點。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM