2016-07-07 167 views
0

首先蟒蛇2.7.11Python的字典追加被覆蓋前一個鍵:值

概述,我收集的目錄名稱在給定的路徑,並把它們傳遞到子CMD。從該子進程中,我逐行遍歷輸出,目錄名稱是鍵,subprocess.stdout是值。

我需要的是保持鍵相同,但保存唯一值並將它們添加到字典中,以便稍後可以寫入csv。

將其顯示2個方法的代碼片斷我已經嘗試過(一個被註釋掉)。兩者都覆蓋字典中現有的key:值。

data = [] 
for dname in listdir(path): 
    header = dname 
    if isfile: 
     entrydict = dict() 
     cmd = "ct lsh -fmt \"%u \\n\" -since 01-Oct-2015 -all " + dname 
     # output of cmd is "name \r\n" 
     p1 = subp.Popen(cmd, stdout=subp.PIPE, stderr=subp.PIPE) 
     usr = [] 
     for name in iter(p1.stdout.readline, ''): 
      if name.rstrip() not in usr: 
       usr.append(name.rstrip()) 
      else: 
       entrydict[header] = usr 

     for n in usr: 
      entrydict[header] = n 
      data.append(entrydict) 

謝謝!

+1

字典一次只能取一個唯一的字典。所以你不能將所有的值賦給key'header'。 –

回答

1

是的,你可以收集所有的唯一值的像names = ['f0', 'f1', 'f2']列表,然後將其與header分配給你的字典作爲重點喜歡

entrydict[header] = names 

只要確保所有的header是不同的。