2016-05-13 225 views
1

我正在嘗試創建一個python腳本,並且卡住了字典。我已經閱讀了其他一些論壇,但似乎無法找到任何地方。我是一個非常新的Python程序員,所以請溫和。將列表值添加到字典鍵

我想要做什麼:

1)建立這樣一個字典:{'Name':'userid','jobid:jobid','walltime:walltime,'nodes:nds'}

2)通過從創建的條目和外部函數調用的列表迭代和提取信息來填充字典

3)問題:我無法弄清楚如何添加條目到合適的鍵

例如,我想這一點:

{‘Name’:’jose’,’jobid’:’001,002,003,005’,’walltime:32:00,240:00,04:00,07:00’,’nodes’:32,32,500’} 

注意一個用戶ID,我有多個jobids,walltimes和節點。
(len(jobids)==len(walltimes)==len(nodes)對於任何一個用戶ID,但可以在用戶ID會發生變化)

我能夠拿到劇本找到每個用戶名的第一個值,但它永遠不會追加。我怎樣才能得到這個追加?

這是我曾嘗試

from collections import defaultdict 
pdict = defaultdict(list) 

start the loop: 

# get new values – add these to the dictionary keyed 
# on username (create a new entry or append to existing entry) 
    … 
    (jobid,userid,jobname, sessid, nds, tsk, walltime,rest)= m.groups() 

    ... 
    if userid in pdict: 
     print "DEBUG: %s is currently in the dictionary -- appending entries" %(userid) 
     pdict[userid][‘jobid’] = pdict[userid][jobid].append(jobid)  I 
    # repeat for nodes, walltime, etc 

    if not userid in pdict: 
     print "DEBUG: %s is not in the dictionary creating entry" %(userid) 
     pdict[userid] = {} # define a dictionary within a dictionary with key off userid 
     pdict[userid]['jobid'] = jobid 
     pdict[userid]['jobname'] = jobname 
     pdict[userid]['nodes'] = nds 
     pdict[userid]['walltime'] = walltime 

我知道這是錯誤的,但無法弄清楚如何獲得追加的工作。我已經嘗試了許多在這個網站上提供的建議。我需要追加(字典中)從循環中鍵入的最新值

以下是輸出示例 - 它不爲每個用戶標識附加多個條目,而是僅爲每個用戶標識添加第一個值

userid jmreill contains data: {'nodes': '1', 'jobname': 'A10012a_ReMig_Q', 'walltime': '230:0', 'jobid': '1365582'}

userid igorysh contains data: {'nodes': '20', 'jobname': 'emvii_Beam_fwi6', 'walltime': '06:50', 'jobid': '1398100'}

有什麼建議嗎?這應該很容易,但我無法弄清楚!

+0

您是否收到錯誤消息?也許'AttributeError:'str'對象沒有屬性'append''?你必須爲保存多個值的鍵創建列表,然後你可以'append()'。所以像'pdict [userid] ['jobid'] = [jobid]' – Jasper

+0

這樣的東西,如果userid不在pdict而不是'if userid in pdict'中, – SparkAndShine

回答

0

密鑰'jobid'對應的值應該是字符串列表而不是字符串。如果你創建你的字典這樣,你就可以將新的作業ID對列表只需:

pdict[userid]['jobid'].append(jobid) 
0

我不記得了解釋爲什麼要使用下面的代碼lambda表達式,但你必須定義的defaultdict a defaultdict

pdict = defaultdict(lambda: defaultdict(list)) 

pdict[userid][‘jobid’].append('1234') 

將工作。

0

append()方法不返回列表...它被修改。另外,你需要爲列表(用方括號)來初始化元素:

if userid in pdict: 
    print "DEBUG: %s is currently in the dictionary -- appending entries" %(userid) 
    pdict[userid][jobid].append(jobid) ## just call append here 
# repeat for nodes, walltime, etc 

if not userid in pdict: 
    print "DEBUG: %s is not in the dictionary creating entry" %(userid) 
    pdict[userid] = {} # define a dictionary within a dictionary with key off userid 
    pdict[userid]['jobid'] = [jobid,] ## initialize with lists 
    pdict[userid]['jobname'] = [jobname,] 
    pdict[userid]['nodes'] = [nds,] 
    pdict[userid]['walltime'] = [walltime,] 
0

追加不返回一個值,它會修改到位名單,你忘了引號「作業ID」上的權利等於。所以你應該用pdict[userid]['jobid'].append(jobid)代替pdict[userid][‘jobid’] = pdict[userid][jobid].append(jobid)。還要考慮@Jasper的評論。

1
from collections import defaultdict 

pdict = defaultdict(dict) 

start the loop: 

# get new values – add these to the dictionary keyed 
# on username (create a new entry or append to existing entry) 
    … 
    (jobid,userid,jobname, sessid, nds, tsk, walltime,rest)= m.groups() 

    ... 
    if userid in pdict: 
     print "DEBUG: %s is currently in the dictionary -- appending entries" %(userid) 
     pdict[userid][jobid].append(jobid) 
    # repeat for nodes, walltime, etc 

    if userid not in pdict: 
     print "DEBUG: %s is not in the dictionary creating entry" %(userid) 
     pdict[userid]['jobid'] = [jobid] 
     pdict[userid]['jobname'] = jobname 
     pdict[userid]['nodes'] = nds 
     pdict[userid]['walltime'] = walltime 
+0

並用'pdict [userid] ['jobid'] = [jobid]替換'pdict [userid] ['jobid'] = jobid'' – SparkAndShine

+0

@sparkandshine是的!謝謝。 – malbarbo

0

您正在尋找一個字典詞典?AutoVivification是完美的解決方案。在Python中實現perl的autovivification功能。

class AutoVivification(dict): 
    """Implementation of perl's autovivification feature.""" 
    def __getitem__(self, item): 
     try: 
      return dict.__getitem__(self, item) 
     except KeyError: 
      value = self[item] = type(self)() 
      return value​ 

這使得一切都變得簡單。請注意,pdict[userid]['jobid']的值應爲列表[jobid]而不是變量jobid,因爲您有多個jobid

pdict = AutoVivification() 

if userid in pdict: 
    pdict[userid]['jobid'].append(jobid) 
else: 
    pdict[userid]['jobid'] = [jobid] # a list 

參照What is the best way to implement nested dictionaries in Python?