2017-02-16 110 views
-1

我卡上做文章,試圖重新格式化的字典如何格式化的字典蟒蛇

這裏是我的代碼,該代碼編寫字典:

deLimit = "**" 
hashKey = item1 +deLimit+ item2 +deLimit+ item3 +deLimit+ item4 

mydict[hashKey] = { 
    「key」: currentTotal + 1 
        } 

with open(file,’a’) as newfile: 
    print 「heading1 heading2 heading3 heading4 heading5」 
    for key, val in myDict.iteritems(): 
     print(repr((key.split('**'), val))) 

結果:

heading1 heading2 heading3 heading4 heading5 
([‘item1’, ‘item2’, ‘item3’, ‘item4’], {‘key’: 1}) 
([‘item1’, ‘item2’, ‘item3’, ‘item4’], {‘key’: 1}) 
([‘item1’, ‘item2’, ‘item3’, ‘item4’], {‘key’: 1}) 

我知道再版讓我的字典的一個很好的格式。但是,我如何重新格式化輸出?

我正在尋找實現的是:

heading1 heading2 heading3 heading4 heading5 
item1 item2 item3 item4 keyValue 
item1 item2 item3 item4 keyValue 
item1 item2 item3 item4 keyValue 
item1 item2 item3 item4 keyValue 
item1 item2 item3 item4 keyValue 
… 

但我不知道如何重新格式化此輸出

([‘item1’, ‘item2’, ‘item3’, ‘item4’], {‘key’: 1}) 

感謝

+0

你不知道。您迭代結構並生成您自己的輸出。 –

+0

「myDict」的結構是什麼? – Rohanil

+0

你的「myDict」是什麼樣的? –

回答

2

你可以使用像這樣的東西:

for key, val in myDict.iteritems(): 
    print (key.replace('**', ' ') + ' ' + str(val['key'])) 
+0

,讓我試着走這回,讓我知道如果這是正確的所以key.replace,是刪除我的星號內的任何地方,並添加一個空格。然後在打印鍵的值之前添加一個空格。 – chowpay

+0

是的,你是對的。 – Rohanil

1
for key, val in mydict.items(): 
    print(",".join(key.split('**')),val['key'],sep=",") 
+0

我收到此錯誤: 'print(「,」。join(key.split('**')),val ['hits'],不知道如何格式化這個響應,但胡蘿蔔在「sep」下面說它的無效語法 – chowpay

+0

我的python版本是3.5,也許這就是原因。 –

+1

爲Python 2.x中,你可以改變它想:'打印 「」。加入(key.split( '**')),STR(VAL [ '關鍵'])' – Rohanil