我正在尝试创建一个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,我有多个JobID,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
这是输出的示例–它不会为每个用户ID附加多个条目,而是仅为每个用户ID取第一个值
userid jmreill包含以下数据:{'nodes':'1','jobname':
'A10012a_ReMig_Q','walltime':'230:0','jobid':'1365582'}
userid igorysh包含以下数据:{'nodes':'20','jobname':
'emvii_Beam_fwi6','walltime':'06:50','jobid':'1398100'}
有什么建议么?这应该很简单,但我无法弄清楚!
最佳答案
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
关于python - 将列表值追加到字典键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37217652/